Tkinter filedialog breaks entry widgets

喜欢而已 提交于 2020-12-27 05:48:54

问题


tl;dr: When the application calls tkinter.filedialog, entry fields do not properly focus.

Long explanation:

When initializing a tkinter application, the entry fields are enabled by default. Their state is tk.ENABLED, they can be focused on by scrolling through fields with tab, and, most importantly, they can be clicked on to select the field.

For some reason, this behavior is broken by calling tkinter.filedialog. If a method of tkinter.filedialog is called, such as askdirectory or askopenfile(), the entry field will still have the tk.ENABLED state, and the background will be properly styled, but clicking on the entry field will not insert the cursor or select the field. Typing, of course, does not register.

This can be worked around by toggling to a different window and toggling back. However, the file dialog windows (properly) return the user directly back to the main window, and so users are always presented with a main window that appears to be locked up.

See this example:

import tkinter as tk
from tkinter import filedialog

BR8K = True

root = tk.Tk()

if BR8K:
    filedialog.askdirectory()

entry = tk.Entry(root, takefocus=True, highlightthickness=2)
entry.grid(sticky="WE")


root.mainloop()

Here, the code behaves properly if BR8K is False, and incorrectly if BR8K is True.

(Note: In a production environment, this would be object oriented. The issue persists in an object oriented environment.)


回答1:


This is a known issues resulting from a dialog window being called prior to the mainloop() being reached for the first time.

The simplest way to fix this is to add update_idletask() before the dialog.

Try this:

import tkinter as tk
from tkinter import filedialog

BR8K = True

root = tk.Tk()
# By adding this you avoid the focus breaking issue of calling dialog before the mainloop() has had its first loop.
root.update_idletasks() 

if BR8K:
    filedialog.askdirectory()

entry = tk.Entry(root, takefocus=True, highlightthickness=2)
entry.grid(sticky="WE")


root.mainloop()


来源:https://stackoverflow.com/questions/54117252/tkinter-filedialog-breaks-entry-widgets

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