首页 > 解决方案 > 首次打开窗口时无法单击 Tkinter 文本框

问题描述

因此,当我第一次打开窗口时,其他一切都很好,我可以单击按钮,但是当我尝试单击文本框并在里面输入内容时,光标没有出现,我也无法输入任何内容。但是,如果我切换到任何其他窗口(实际上是从 chrome 到记事本的任何内容)并切换回来,我就可以在文本框中正常输入。

我不知道如何解决这个问题。有人可以帮我吗?我的 Python 版本是 3.8.0。

这是我的代码的一部分,“top”是我的 tkinter 窗口的变量名。inputtxt1 和 inputtxt2 是我遇到问题的文本框。

load_txt.set("analyze")
a_bt = Button(top, text = "analyze", command = _analyze_)
a_bt.config(textvariable=load_txt)
a_bt.grid(row=4, column=0, sticky='E')
dir_bt = Button(top, text = "change dir", command = ch_dir)
dir_bt.grid(row=4, column=1, sticky='W')
save_button['command'] = save_change
save_button.grid(row=5, column=0, sticky='E')
top.geometry("600x1000")
top.resizable(width = True, height = True)

Label(top, text = "start_slab").grid(row=0, column=0, sticky='E')     
inputtxt1 = Text(top, height = 1, width = 5, state='normal')
inputtxt1.grid(row=1, column=0, sticky='E')

Label(top, text = "end_slab").grid(row=2, column=0, sticky='E')
inputtxt2 = Text(top, height = 1, width = 5, state='normal')
inputtxt2.grid(row=3, column=0, sticky='E')

avg_bt = Button(top, text = "avg", command = show_avg)
prev_bt = Button(top, text = "prev", command = show_prev)
next_bt = Button(top, text = "next", command = show_next)
#panel.pack()

dir_name = askdirectory()

top.bind("<Return>", analyze)

top.grid_rowconfigure(0, weight=0)

top.mainloop()

谢谢!

===========编辑===========

这是代码的简短工作版本

from tkinter.filedialog import askdirectory
from tkinter import Tk, Label, Button, Text

frame_idx = 0
dir_name = None

top = Tk()
save_button = Button(top, text = "save images")

a_bt = Button(top, text = "analyze")
a_bt.grid(row=4, column=0, sticky='E')
dir_bt = Button(top, text = "change dir")
dir_bt.grid(row=4, column=1, sticky='W')
save_button.grid(row=5, column=0, sticky='E')
top.geometry("600x1000")
top.resizable(width = True, height = True)

Label(top, text = "start_slab").grid(row=0, column=0, sticky='E')     
inputtxt1 = Text(top, height = 1, width = 5, state='normal')
inputtxt1.grid(row=1, column=0, sticky='E')

Label(top, text = "end_slab").grid(row=2, column=0, sticky='E')
inputtxt2 = Text(top, height = 1, width = 5, state='normal')
inputtxt2.grid(row=3, column=0, sticky='E')

dir_name = askdirectory()


top.grid_rowconfigure(0, weight=0)

top.mainloop()

似乎当我没有 askdirectory 功能时,这不会成为问题,但如果我这样做,就会出现问题。

标签: python-3.xtkinter

解决方案


添加top.update()ortop.update_idletasks()之前dir_name = askdirectory()。我认为这会askdirectory干扰条目,因此它们会停止处理事件,直到它们在屏幕上重绘(当您重新聚焦窗口时)。那可能是一个tcl错误?我不知道 tcl 在askdirectory被调用时如何处理事件。


推荐阅读