在条目框外部单击时如何禁用条目小部件

问题描述 投票:0回答:1

我正在使用 Tkinter 模块在 Python 3 中制作 GUI 应用程序。我的应用程序包含一个用户可以输入内容的输入小部件。唯一的问题是,当用户完成输入并在输入框外部单击时,输入框不会被禁用。我尝试使用 Entry Widget 的状态参数做一些事情,但我不知道如何处理它。

我将如何实现此功能?

这是我的代码的样子:

from tkinter import*

tk = Tk()
tk.minsize(250, 300)
tk.resizable(False, False)

val = StringVar()
val.set(100)

user_input = Entry(tk, textvariable=val, width=22)

user_input.place(x=100, y=83)

tk.mainloop()
python python-3.x tkinter
1个回答
0
投票

您可以使用

bind()
将函数分配给
Entry
,当有事件
<FocusOut>
时就会执行该函数。并且这个功能可以禁用
Entry

但是禁用的小部件无法使用

<FocusIn>
进行聚焦,因此它将始终禁用,您将需要例如按钮将其重新激活。这对于用户来说似乎毫无用处且令人烦恼。

基于 Tkinter - 窗口焦点丢失事件

的代码
import tkinter as tk

def on_focus_out(event):
    label.configure(text="I DON'T have focus")
    entry.config(state='disabled')

def on_focus_in(event):
    label.configure(text="I have focus")
    entry.config(state='normal')
    
def on_button_press():
    entry.config(state='normal')
        
root = tk.Tk()

label = tk.Label(root, text="HELLO")
label.pack(fill="both", expand=True)

entry = tk.Entry(root, width=30)
entry.pack(fill="both", expand=True)

button = tk.Button(root, text="OK", command=on_button_press)
button.pack(fill="both", expand=True)

entry.bind("<FocusIn>", on_focus_in)
entry.bind("<FocusOut>", on_focus_out)

root.mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.