用自定义弹出式 Tkinter 对话框的正确方法是什么?
Tkinter 带有许多内置函数和模块,这些函数和模块已在 Python 中实现。Tkinter 中的 MessageBox 模块就是其中一个,它可以在任何应用程序中使用,只需使用其相关函数即可。这些软件包唯一的限制是,我们无法修改或更改 MessageBox 模板。因此,要实现自定义弹出式消息框,我们可以按下列步骤操作:
- 创建一个按钮,并添加一个命令来为此按钮定义一个函数。
- 定义一个函数来创建一个顶级窗口,并在其中添加其他小部件。
- 在顶级窗口中添加按钮和确认标签文本。
- 添加按钮命令,以便在主窗口中交互式地显示一些消息。
示例
# Import required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame
win = Tk()
# Set the window size
win.geometry("700x250")
# Define a function to implement choice function
def choice(option):
pop.destroy()
if option == "yes":
label.config(text="Hello, How are You?")
else:
label.config(text="You have selected No")
def click_fun():
global pop
pop = Toplevel(win)
pop.title("Confirmation")
pop.geometry("700x250")
pop.config(bg="green3")
# Create a Label Text
label = Label(pop, text="Would You like to Proceed?", bg="green3", fg="white", font=('Aerial', 12))
label.pack(pady=20)
# Add a Frame
frame = Frame(pop, bg="green3")
frame.pack(pady=10)
# Add Button for making selection
button1 = Button(frame, text="Yes",
command=lambda: choice("yes"), bg="green")
button1.grid(row=0, column=1)
button2 = Button(frame, text="No",
command=lambda: choice("no"), bg="green")
button2.grid(row=0, column=2)
# Create a Label widget
label = Label(win, text="", font=('Aerial', 14))
label.pack(pady=40)
# Create a Tkinter button
ttk.Button(win, text="Click Here", command=click_fun).pack()]
win.mainloop()输出
执行上述代码将显示带有按钮的窗口。
当我们单击按钮时,它将显示一个自定义弹出消息框
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP