我不是一个有经验的程序员/脚本,这是我第一个包含UI (tkinter)的项目。
我的键盘上有一个键,绑定到一个打开窗口的函数。我用这样的东西把它绑定到键上:
root.bind('<s>', popupmsg)这是我调用的函数:
def popupmsg(msg):
global MSGroot
MSGroot = Tk()
lab1.config("test")
lab1= Label(MSGroot, font=('times', 40), bg='blue', fg="red")
lab1.grid(row=0, column=1)
MSGroot.title("TIME")
MSGroot.call('wm', 'attributes', '.', '-topmost', '1')
MSGroot.mainloop(),这段代码工作,,并显示窗口很好,但我想找到一种优雅的方式,只需打开和关闭该窗口使用相同的键绑定。
有什么建议吗?
发布于 2019-05-23 22:54:53
我会提出许多建议,这将使您的代码更好/更优雅.
首先,不要对弹出窗口使用
Tk()窗口,使用TopLevel()窗口,两个Tk()窗口不能相互传递信息,所以使用TopLevel()窗口代替。
def popupmsg(msg):
global MSGroot
MSGroot = TopLevel(root) # needs the main Tk() window as a master/parent element
lab1.config("test")
lab1= Label(MSGroot, font=('times', 40), bg='blue', fg="red")
lab1.grid(row=0, column=1)
MSGroot.title("TIME")
MSGroot.call('wm', 'attributes', '.', '-topmost', '1')其次,您应该创建类以使您的
Tk和TopLevel窗口更好地格式化您的代码,并且对于更改windows的工作方式更有功能。
class PopUpMsg(Toplevel):
def __init__(self, master, msg):
super(PopUpMsg, self).__init__(master)
lab1 = Label(self, font=('times', 40), bg='blue', fg="red")
lab1.grid(row=0, column=1)
self.title("TIME")
self.call('wm', 'attributes', '.', '-topmost', '1')
# This is now the function you could use to show the popup
def popupmsg(msg):
test_popup = PopUpMsg(root, msg) # This is how you would create the PopUpMsg
test_popup.pack()
root = Tk()
root.mainloop()最后,为了使其如此,当您再次按"s“时,窗口将关闭,我将为这个新的
PopUpMsg类创建一个PopUpMsg方法,并将"s”绑定到它。
class PopUpMsg(Toplevel):
def __init__(self, master):
super(PopUpMsg, self).__init__(master)
lab1 = Label(self, font=('times', 40), bg='blue', fg="red")
lab1.grid(row=0, column=1)
self.title("TIME")
self.bind('<s>', self.on_close)
def on_close(self):
self.destroy()https://stackoverflow.com/questions/56283577
复制相似问题