【发布时间】:2021-10-17 05:10:11
【问题描述】:
我正在尝试为按钮分配一些行为,我已经实现了一些行为,例如:
- 如果鼠标位于按钮上方,则更改按钮的颜色。
- 恢复默认按钮颜色。
- 将最后按下的按钮保存为绿色。
今天我意识到,当我按下一个按钮而不释放点击时,我将鼠标指针从按钮上移开并释放点击,它变成绿色,但没有执行链接功能,我希望按钮不要换颜色 。我试图消除这种行为,但我没有想法。该代码是可执行的,它适用于 python 3.7。谢谢。
from tkinter import *
class TypeButton(Button):
def __init__(self, parent, *args, **kwargs):
kwargs = {'font':('Calibri',9,'bold'), 'bg': '#11161d', 'fg':'white',
'width':10, 'bd':0, 'activebackground':'#bdfe04', **kwargs}
super().__init__(parent, *args, **kwargs)
class Example(Frame):
def __init__(self,parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.frame = Frame(self, bg='#11161d')
self.frame .grid(padx=(10,10), pady=(6,6))
self.container1 = None
self.creator_buttons()
#????????????????
self.bind_all("<B1-Motion>", self.callback)
def creator_buttons(self):
mobiles = [['Frog', 'Fox', 'Boomer', 'Ice', 'J.d', 'Grub', 'Lightning', 'Aduka', 'Knight', 'Kalsiddon', 'Mage'],
['Randomizer', 'Jolteon', 'Turtle', 'Armor', 'A.sate', 'Raon', 'Trico', 'Nak', 'Bigfoot', 'Barney', 'Dragon']]
self.mobiles2 = ['Fox','Knight','Jolteon','Barney','Dragon']
self.buttons22 = []
for index1, mobil in enumerate(mobiles):
for index2, texto in enumerate(mobil):
number = 11 if index1 == 1 else 0
btn = B1ButtonCls (self.frame_1, text=texto, command= self.callback)
n1 = 5 if index2 == 0 else 0
n2 = 5 if index2 == 10 else 0
btn .grid(column=index2 , row=index1 , pady=3, padx=(n1,n2))
btn.bind("<Enter>", self.enter_mouse)
btn.bind("<Leave>", self.leave_mouse)
btn.bind("<Button-1>", self.clic_mouse)
if texto in self.mobiles2: btn.config(fg='yellow')
self.buttons22.append(btn)
def enter_mouse(self, event):
widget1 = event.widget
if not widget1 .cget('bg') == '#bdfe04':
widget1 .config(bg="#24364a")
def leave_mouse(self, event):
if not event.widget .cget('bg') == '#bdfe04':
event.widget.config(bg='#11161d')
def clic_mouse(self, event):
widget1 = event.widget
widget1.config(bg='#bdfe04', fg='black')
if self.container1 is not None and self.container1 != widget1:
if self.container1 .cget('text') in self.mobiles2:
self.container1 .config (bg='#11161d', fg='yellow')
else:
self.container1 .config (bg='#11161d', fg='white')
self.container1 = widget1
def callback(self):
print('Closed')
root = Tk()
app = Example(root).pack()
root.mainloop()
【问题讨论】:
-
您可以尝试将您当前所在的按钮存储在
enter_mouse函数中,然后在调用leave_mouse时将引用替换为例如没有。然后在clic_mouse函数中检查引用是否为无。如果是这样,那么你不执行(返回函数),否则你运行你的代码。 -
@BryanOakley 你知道为什么
B1-Motion对我不起作用,这已经令人沮丧......我正在寻找信息但它不完整,也不够清楚,有人可以解释这里发生了什么?.如果我删除B1它开始工作,这开始很麻烦。有人可以向这个年轻人解释发生了什么吗?
标签: python-3.x tkinter