No input possible after tk

岁酱吖の 提交于 2020-01-22 03:46:19

问题


If have this piece of code:

import Tkinter as tk
import tkFileDialog

menu = tk.Tk()
res = tkFileDialog.askopenfilename() # un-/comment this line
label = tk.Label(None, text="abc")
label.grid(row=0, column=0, sticky=tk.W)
entry = tk.Entry(None)
entry.grid(row=0, column=1, sticky=tk.EW)

res = menu.mainloop()

Note: the askopenfilename is just a dummy input. So Just close it to get to the (now blocked) main window of TK.

When I comment the askopenfilename everything works fine. But with the it, I can not enter data in the entry.

This only happens with Windoze environments. The askopenfilename seems to steal the focus for the main TK window. After clicking a totally different window and back again in the TK window, input is possible.


回答1:


I've seen reports of this before, I think it's a known bug on windows. You need to let mainloop start before you open a dialog.

If you want the dialog to appear when the app first starts up you can use after or after_idle to have it run after mainloop starts up.

For example:

menu = tk.Tk()
...
def on_startup():
    res = tkFileDialog.askopenfilename()

menu.after_idle(on_startup)
menu.mainloop()

If you don't want any other GUI code to execute until after the dialog, move all your code except for the creation of the root window and call to mainloop into on_startup or some other function.

For example:

def main(filename):
    label = tk.Label(None, text="abc")
    label.grid(row=0, column=0, sticky=tk.W)
    entry = tk.Entry(None)
    entry.grid(row=0, column=1, sticky=tk.EW)

def on_startup():
    res = tkFileDialog.askopenfilename()
    main(filename)

root = Tk()
root.after_idle(on_startup)



回答2:


askopenfilenamehas it's own event loop. The programm stops, until you selected a filename, and continues afterwards.



来源:https://stackoverflow.com/questions/37610608/no-input-possible-after-tk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!