这些是我的按钮,我想在鼠标输入某个按钮时更改状态栏的文本。我想只使用一种鼠标输入按钮的方法。怎么做?
self.connectBtn = tk.Button(self.master, text="CONNECT", width=8)
self.connectBtn.place(x=10, y=100)
self.backupBtn = tk.Button(self.master, text="BACKUP", width=8)
self.backupBtn.place(x=80, y=100)
self.copyBtn = tk.Button(self.master, text="COPY", width=8)
self.copyBtn.place(x=10, y=130)
self.moveBtn = tk.Button(self.master, text="MOVE", width=8)
self.moveBtn.place(x=80, y=130)
for self.button in [self.connectBtn, self.backupBtn, self.copyBtn, self.moveBtn]:
self.button.bind("<Enter>", self.mouseOver)
self.button.bind("<Leave>", self.mouseLeave)
我的mouseOver方法
def mouseOver(self, *args):
if self.backupBtn:
self.status['text'] = "Backups the selected database."
elif self.connectBtn:
self.status['text'] = "Copies the selected database."
elif self.button == self.moveBtn:
self.status['text'] = "Moves the selected database."
如果鼠标进入备份按钮,则状态栏中的文本应为&#34;备份所选数据库。&#34;然后在其他按钮上。对于那些按钮,我不知道该怎么用。谢谢!
答案 0 :(得分:0)
这个SO help page建议发布一个最小的,完整的,可验证的例子(人们太少;-)。我建议尝试相同的。从空闲或控制台运行(要打印到的地方)时,以下打印“成功!”每次鼠标进入按钮时。
import tkinter as tk
root = tk.Tk()
but = tk.Button(root, text = 'Hi')
but.pack()
print(but)
def cb(event):
if event.widget == but:
print('Success!')
but.bind('<Enter>', cb)
root.mainloop()
关键点是:回调获得一个参数,一个事件对象;事件有大约20个属性,一个是小部件;可以比较小部件的相等性。应用于您的代码,以下将(应该)工作。
def mouseOver(self, event):
if event.widget == self.backupBtn:
self.status['text'] = "Backs up the selected database."
elif event.widget == self.connectBtn:
self.status['text'] = "Connects to the selected database."
...
但是,我个人会进一步考虑代码。
action = {self.backupBtn: 'Backs up', self.connectBtn: 'Connects to',
self.moveBtn: 'Copies', self.moveBtn: 'Moves'}
def mouseOver(self, event):
self.status['text'] = "%s the selected database." % action[event.widget]