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

时间:2014-08-03 15:24:04

标签: python tkinter tkinter-entry filedialog

当我运行此代码时,文件选择器出现,然后当我完成它时,我无法输入条目小部件,直到我专注于另一个窗口然后再回来。为什么会这样?

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()

2 个答案:

答案 0 :(得分:1)

您只需在box.focus_force()下方写上box.pack(),即可为您完成工作。

答案 1 :(得分:0)

这应该解决它

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即可立即使用该框。