【问题标题】:Tkinter Entry widget in Python is uneditablePython 中的 Tkinter Entry 小部件不可编辑
【发布时间】:2014-09-26 04:30:19
【问题描述】:

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

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

【问题讨论】:

  • 你是在 OSX 上运行这个吗?
  • 我不知道为什么,但我想你可以先做 askopenfilename 然后 mainloop start...
  • 我不在 OSX 上,我在 Windows 7 和 8.1 上。在 askopenfilename 窗口关闭之前,我怎样才能让主循环不启动?
  • 在 askopenfilename 关闭之前不运行主循环几乎是不可能的,因为它总是需要一个根窗口或主窗口,因此您可以创建一个临时窗口并执行 root.withdraw()
  • 入口小部件的东西可能是 Python 2 中的一个错误,所以我会考虑更新到 Python 3 并在那里使用那个 tkinter。

标签: python tkinter tkinter-entry filedialog


【解决方案1】:

您需要执行 2 个步骤:

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

你会很高兴的!

【讨论】:

    【解决方案2】:

    您只需在box.pack() 下方写下box.focus_force(),这应该可以为您完成工作。

    【讨论】:

      【解决方案3】:

      这应该可以解决它

      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_set 和focus_force,您可以让盒子立即投入使用。

      【讨论】:

      • 这并没有解决问题。我正在做类似的事情,但这仍然给我带来了麻烦。你有其他想法吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-16
      • 2012-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多