我有一个带有许多按钮的Python Tkinter Windows程序。我需要一个按钮来改变它的背景颜色来回时,指针是在它和关闭它。这个问题以前在这里讨论过,我尝试使用给出的代码片段来解决我的问题,但没有成功。对我来说,最好的解决方案是,该方法的级别仅需要一次。在我的程序中,用户可以定义按钮的背景色,但与所有按钮类似,并且颜色上的指针应该能够受到选择的影响
下面是我尝试使用bind的最简单的代码。randint模拟用户选择。但是,正如前面所说,它不起作用。我需要什么改变?我是Python和Tkinter的新手,所以请给出您的答案,对下面的代码进行明确的更改
import tkinter as tk
from random import randint
class PointerOnOff:
def __init__ (self, root):
root.geometry ("200x140+100+100")
color = randint (0, 2)
if color == 0:
off_color = "#aaffaa"
on_color = "#99ff99"
elif color == 1:
off_color = "#ffffaa"
on_color = "#ffff99"
else:
off_color = "#ffaaaa"
on_color = "#ff9999"
self.OK = tk.Button (root, text = "OK", bg = off_color, command = self.OKPush)
self.OK.place (x = 50, y = 20, width = 100, height = 30)
self.Cancel = tk.Button (root, text = "Cancel", bg = off_color, command = self.CancelPush)
self.Cancel.place (x = 50, y = 60, width = 100, height = 30)
self.PushedButton = tk.Label (root, text = "")
self.PushedButton.place (x = 20, y = 100, width = 160, height = 30)
def on_enter (anybutton):
anybutton.widget.config (bg = on_color)
def on_leave (anybutton):
anybutton.widget.config (bg = off_color)
self.OK.bind("<Enter>", on_enter)
self.OK.bind("<Leave>", on_leave)
self.Cancel.bind("<Enter>", on_enter)
self.Cancel.bind("<Leave>", on_leave)
def OKPush (self):
self.PushedButton.config (text = "You pushed OK button")
def CancelPush (self):
self.PushedButton.config (text = "You pushed Cancel button")
root = tk.Tk ()
master = PointerOnOff (root)
root.mainloop ()
我是python初学者,我不确定我的答案,但我认为更改背景颜色的代码如下:
问题是由于两个函数的缩进不正确:
on_enter()
和on_leave()
。它们必须是__init__()
内的内部函数:如果不想为每个按钮调用两个绑定,最好创建一个自定义按钮类来嵌入悬停功能:
然后,将此自定义按钮类用于希望具有悬停效果的按钮:
相关问题 更多 >
编程相关推荐