Python Tkinter按钮未注册单击
我有下面的tkinter按钮类Python Tkinter按钮未注册单击,python,tkinter,Python,Tkinter,我有下面的tkinter按钮类 import tkinter as tk class Button(GraphicsObject): """A button is a labeled rectangle in a window. It is activated or deactivated with the activate() and deactivate() methods. The clicked(p) method returns true if the button is acti
import tkinter as tk
class Button(GraphicsObject):
"""A button is a labeled rectangle in a window.
It is activated or deactivated with the activate()
and deactivate() methods. The clicked(p) method
returns true if the button is active and p is inside it."""
def __init__(self, p, width, height, label):
""" Creates a rectangular button, eg: qb = Button(myWin, Point(30,25), 20, 10, 'Quit') """
GraphicsObject.__init__(self, [])
self.anchor = p.clone()
w,h = width/2.0, height/2.0
self.x, self.y = p.getX(), p.getY()
self.xmax, self.xmin = self.x+w, self.x-w
self.ymax, self.ymin = self.y+h, self.y-h
p1 = Point(self.xmin, self.ymin)
p2 = Point(self.xmax, self.ymax)
self.width = width
self.height = height
self.rect = Rectangle(p1,p2)
self.label = label
self.fill = "white"
self.color = "black"
self.font = DEFAULT_CONFIG['font']
self.activate()
def _draw(self, canvas, options):
p = self.anchor
x,y = canvas.toScreen(p.x,p.y)
#frm = tk.Frame(canvas.master,height = self.height, width = self.width,)
# frm.pack_propagate(0)
#frm.pack()
self.button = tk.Button(canvas.master,
height = self.height,
width = self.width,
text = self.label,
bg = self.fill,
fg = self.color,
font=self.font)
self.button.place(x = self.x, y = self.y, height =self.height, width = self.width)
#self.setFill(self.fill)
self.button.focus_set()
#return canvas.create_window(x,y,window=self.button)
def clicked(self, p):
""" RETURNS true if button active and p is inside"""
return self.active and \
self.xmin <= p.getX() <= self.xmax and \
self.ymin <= p.getY() <= self.ymax
def getLabel(self):
"""RETURNS the label string of this button."""
return self.label.getText()
def setColor(self, color):
self.color = color
def setFill(self, color):
self.fill = color
def activate(self):
"""Sets this button to 'active'."""
self.color = 'black'
self.rect.setWidth(2)
self.active = 1
def deactivate(self):
"""Sets this button to 'inactive'."""
self.color = 'darkgrey'
self.rect.setWidth(1)
self.active = 0
当我运行我的程序时,按钮会正确地显示在窗口上,只要我没有在按钮内部单击,它就会注册一个单击值False。但是,当我点击按钮时,什么也没发生。
print(clicked)
和print(clicked==True)
单击时从不运行的值应为True。我是否需要修改我的类,还是在尝试创建按钮时忘记包含一些内容 最后一段代码会干扰tkinter的主循环吗?在使用TKInter时,通常不应该有连续的while循环。单击按钮时,单击是否应该为True?不,单击事件首先在mainloop中处理,它被while循环阻止。您能告诉我如何在我的代码中使用mainloop吗?我可以使用mainloop实现相同的输出吗?再想一想,只需绑定按钮事件,您似乎没有对按钮做任何特殊的操作
sign_in_button = Button(Point(237.5,300),80,40,'Sign In')
sign_in_button.draw(login_page)
click_point = login_page.getMouse()
clicked = sign_in_button.clicked(click_point)
print(clicked)
while(clicked == False):
click_point = login_page.getMouse()
clicked = sign_in_button.clicked(click_point)
print(clicked)
print("clicked == True")