Python中的Tkinter Entry部件是不可编辑的



当我运行这段代码时,出现了文件选择器,然后当我完成它时,我无法键入条目小部件,直到我关注另一个窗口,然后再返回。为什么会发生这种情况?

import tkinter as tk
from tkinter.filedialog import askopenfilename

location = ''
start = tk.Tk()
tk.Label(text='What is the name of your table?').pack()
box = tk.Entry(start, exportselection=0, state=tk.DISABLED)
box.pack()
button = tk.Button(start, text='OK', command=lambda e: None)
button.pack()
location = askopenfilename(defaultextension='.db', 
                           title="Choose your database", 
                           filetypes=[('Database Files', '.db'), ('All files', '*')])
box.config(state=tk.NORMAL)
start.mainloop()

你只要把box.focus_force()写在box.pack()下面就可以了。

您需要遵循两个步骤:

  1. box.focus_force()写在box.pack()下面
  2. 剪切代码location = askopenfilename(blah blah..)并粘贴到start = tk.Tk()

你会好起来的!

这应该可以修复它

import tkinter as tk
from tkinter.filedialog import askopenfilename
location = ''
root = tk.Tk()
root.withdraw()
location = askopenfilename(defaultextension='.db', title="Choose your database", filetypes=[('Database Files', '.db'), ('All files', '*')])
start = tk.Tk()
tk.Label(start, text='What is the name of your table?').pack()
box = tk.Entry(start, exportselection=0, state=tk.DISABLED)
box.pack()
start.focus_set()
box.focus_set()
start.focus_force()
button = tk.Button(start, text='OK', command=lambda e: None)
button.pack()
box.config(state=tk.NORMAL)
start.mainloop()

先运行askopenfilename可以避免这个问题。

这样做,你需要创建一个root窗口并撤回它,否则你将得到两个窗口。

通过使用focus_setfocus_force,您可以使盒子立即准备好使用

最新更新