繁体   English   中英

当用户单击 tkinter 中的错误消息框时,聚焦空输入框

[英]Focusing the empty entry box when user clicks the error messagebox in tkinter

在 tkinter GUI 中,我创建了一个“注册帐户”window。 如果用户在一个或多个条目(在条目框中)未填写的情况下单击注册按钮,则会出现一个错误消息框。 我想要的是,当用户单击 tkinter 错误消息框的“确定”按钮时,cursor 应该移动到那个特定的空输入框,从而指示用户哪个输入框是空的。

from tkinter import *
import tkinter.messagebox

class MyGUI:
def __init__(self):
    self.root = Tk()

    self.entrybox = []

    for i in range(9): #Creating 9 Entry Boxes
        self.entrybox.append(Entry(self.root, width = 10, font = 'Verdana 10'))

    for i in self.entrybox: #packing each Entry Box      
        i.pack(pady = 5)

    okButton = Button(self.root, text = 'OK', command = self.get_entryvalues)
    okButton.pack()

    mainloop()

def get_entryvalues(self):
    values = []
    for i in self.entrybox:
        values.append(i.get())
    if '' in values:
        tkinter.messagebox.showerror('Error', '1 or more entries are not filled!', parent = self.root)
    else:
        tkinter.messagebox.showinfo('Info', 'Form submitted', parent = self.root)


mygui = MyGUI()

由于您没有包含任何代码,因此这里有一个片段可以帮助您完成。

from tkinter import *
from tkinter import messagebox

root = Tk()


def something():
    if e.get() == '':
        messagebox.showerror('Error message box',
                             'Please fill the blank field', parent=root)
        e.focus_force() #to get the lost focus back


l = Label(root, text='Snippet')
l.pack()

e = Entry(root)
e.pack(pady=10)

b = Button(root, text='Click me!!', command=something)
b.pack()

e.focus_force()  # to have focus to the entry box wen the program starts

root.mainloop()

在这里,如果您的输入字段为空白,它会显示一个消息框,在您单击确定后,焦点会返回到 window 的输入框。

如果您只有 1 个messagebox ,则消息框中的parent参数是完全可选的,但它会重点关注消息框出现的 window(如果您正在使用超过 1 个 Z05B8C74CBD96FBF2DE4C1A352702FBF4

如果有任何问题或您有疑问,请告诉我:D

您可以在get_entryvalues() function 中的 for 循环中找到的第一个空条目上调用focus()

from tkinter import *
import tkinter.messagebox

class MyGUI:
    def __init__(self):
        self.root = Tk()

        self.entrybox = []
        for i in range(9): #Creating 9 Entry Boxes
            btn = Entry(self.root, width=10, font='Verdana 10')
            btn.pack(pady=5)
            btn.bind('<Return>', self.next_entry)
            self.entrybox.append(btn)

        okButton = Button(self.root, text='OK', command=self.get_entryvalues)
        okButton.pack()

        self.root.mainloop()

    def get_entryvalues(self):
        for e in self.entrybox:
            if e.get().strip() == '':
                tkinter.messagebox.showerror('Error', '1 or more entries are not filled!', parent=self.root)
                e.focus() # focus the empty entry
                return
        tkinter.messagebox.showinfo('Info', 'Form submitted', parent=self.root)

    def next_entry(self, event):
        event.widget.tk_focusNext().focus()

mygui = MyGUI()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM