How to make a tkinter Entry field mandatory to enter some text?

孤人 提交于 2020-12-13 03:26:30

问题


like in HTML tag attribute required=required

I want make an Entry widget mandatory, the user must enter data in it, otherwise don't proceed to next step.

How to do it with tkinter?


回答1:


There is no attribute "required" in Tkinter, you need to write a function to check whether the user entered data in the entry or not. Then use this function as the command of the "Next" button.

import tkinter as tk

def next_step():
    if mandatory_entry.get():
        # the user entered data in the mandatory entry: proceed to next step
        print("next step")
        root.destroy()
    else:
        # the mandatory field is empty
        print("mandatory data missing")
        mandatory_entry.focus_set()

root = tk.Tk()

mandatory_entry = tk.Entry(root)

tk.Label(root, text="Data *").grid(row=0, column=0)
mandatory_entry.grid(row=0, column=1)
tk.Button(root, text='Next', command=next_step).grid(row=1, columnspan=2)

root.mainloop()



回答2:


Without your own function its not possible

from tkinter import *
def check_empty() :
     if entry.get():
         pass     #your function where you want to jump
     else:
        print(' input required') 


mw=Tk()
Txt=Lable(mw, text='enter data').pack()
entry=Entry(mw, width=20).pack()
Btn=Button(mw, text='click', command=check_empty).pack()
mw.mainloop()

If you have single field then jump to a new function or class else if multiple entry blocks then use pass if successfully written some data in the entry field

Remember above code will check multiple fields at the same time after clicking the button.



来源:https://stackoverflow.com/questions/43271056/how-to-make-a-tkinter-entry-field-mandatory-to-enter-some-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!