我正在开发一个使用Tkinter和canvas小部件的界面,到目前为止,我已经从其他问题和发布的答案中找到了问题的答案,但我在这个问题上遇到了麻烦。在
我在创建GUI元素的类中有几个键盘绑定,在程序启动时它们都能正常工作。绑定看起来像这样:self.canvas.get_tk_widget().bind("",self.flash_open)
和都在类的init帴函数中。从昨天开始,我初始化了这个类
要启动程序,然后等待用户从菜单中选择“打开”,然后打开(除其他外)tkmessagebox
^{pr2}$
有了这个文件名,我就可以从某个文件类型(与问题无关)中检索所需的变量名。今天,我修改了\uu init_uu函数,以便在程序启动时调用open函数。由于在打开此文件之前无法执行其他操作,因此首先打开它是有意义的。一旦选择了文件并关闭了Tkmessagebox,根窗口就处于活动状态,但是键盘绑定都不起作用。我的功能仍然可以使用分配给它们的菜单/按钮,只是没有绑定。我尝试过将快捷方式绑定到根目录,结果是相同的,现在我想这可能是我调用它们的顺序有问题def __init__(self):
...
self.openfile() #calls the tkmessagebox
self.root.mainloop() #starts gui
我以前实际上遇到过这个问题,toplevel()实例被关闭/销毁并禁用了父窗口的绑定。没有任何错误消息可以说,绑定只是不做任何事情。我还应该提到,我已经尝试再次使用self.openfile()
self.root.mainloop()
self.root.focus_set()
我以前就解决了这个问题,方法是使用wm_cture()和wm_deconify()函数简单地隐藏子窗口,然后在程序完成后关闭它。不过,在这种情况下,这个修复程序要稍微困难一些。如果有人能解释一下问题的起因,我将不胜感激。在
编辑:
我写了一个可运行的代码段来确切地说明我的问题所在。在import os
from tkFileDialog import askopenfilename
from Tkinter import *
class Start:
def __init__(self):
self.root = Tk()
self.root.title('Binding Troubles')
menubar = Menu(self.root)
#add items and their commands to the menubar
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Do work", command=self.do_work)
filemenu.add_command(label="Open File",command=self.openfile)
menubar.add_cascade(label="File", menu=filemenu)
#bind control-o to perform the do work function
self.root.bind("",self.flash_do_work)
self.root.bind("",self.flash_do_work)
#add the menubar to the GUI
self.root.config(menu=menubar)
#initially open a tkdialog to open a file
self.openfile()#comment out this line to make the bind work
self.root.focus()#also tried self.root.focus_set()
self.root.mainloop()
def flash_do_work(self,event):
#indirect tie to the do_work() function, I'm don't know a
#proper way to make functions handle calls from both events and non-events
self.do_work()
def openfile(self):
#gets current path
self.pathname = os.getcwd()
#Requests filename using a tkdialog
self.filename =askopenfilename(initialdir= self.pathname)
print self.filename
def do_work(self):
#placeholder for actual function; shows whether the bind is working or not
print "work"
Start()
如果self.openfile文件()已从“初始化”中删除,仅从菜单中使用
另一个编辑:我再次更新了示例,给出了一个运行openfile()函数的菜单选项。我注意到,如果openfile()在\uyu init\uu中被调用,绑定将不起作用。但是如果接下来再次调用openfile函数,这次是从菜单手动调用,绑定将再次开始工作。不知道该从中得到什么。另外,我很抱歉帖子太长了。在