在 tkinter 中创建带有输入字段的弹出消息框

Tkinter Popup 是顶层窗口界面,将小部件和元素与主窗口一起包装起来。它可以使用像 Button Widget 这样的处理程序嵌入到任何主窗口中。可以使用Toplevel(root)构造函数创建弹出窗口。

示范

在此示例中,我们将创建一个简单的应用程序,其中包含一个标签 小部件和一个用于打开包含输入 字段的弹出消息框的按钮。打开弹出窗口后,它可以具有返回主窗口的功能。

#Import the required library
from tkinter import*

#Create an instance of tkinter frame
win= Tk()

#Define geometry of the window
win.geometry("750x250")

#Define a function to close the popup window
def close_win(top):
   top.destroy()
def insert_val(e):
   e.insert(0, "你好世界!")

#Define a function to open the Popup Dialogue
def popupwin():
   #Create a Toplevel window
   top= Toplevel(win)
   top.geometry("750x250")

   #Create an Entry Widget in the Toplevel window
   entry= Entry(top, width= 25)
   entry.pack()

   #Create a Button to print something in the Entry widget
   Button(top,text= "Insert", command= lambda:insert_val(entry)).pack(pady= 5,side=TOP)
   #Create a Button Widget in the Toplevel Window
   button= Button(top, text="Ok", command=lambda:close_win(top))
   button.pack(pady=5, side= TOP)
#Create a Label
label= Label(win, text="Click the Button to Open the Popup Dialogue", font= ('Helvetica 15 bold'))
label.pack(pady=20)

#Create a Button
button= Button(win, text= "点击我!", command= popupwin, font= ('Helvetica 14 bold'))
button.pack(pady=20)
win.mainloop()
输出结果

运行上面的代码将显示一个窗口,其中包含一个用于打开弹出对话框的按钮。

单击该按钮后,它将打开弹出对话框。弹出对话框有两个按钮,每个按钮用于不同的目的。当我们单击“确定”按钮时,它将销毁弹出窗口并返回到主窗口。