如何在tkinter中创建模态对话框?

如何在tkinter中创建模态对话框?

对话框是任何应用程序中非常重要的组件。通常用于与用户和应用程序界面交互。我们可以使用Toplevel窗口和其他小部件为任何tkinter应用程序创建对话框。顶层窗口弹出了所有其他窗口上面的东西。因此,我们可以在顶层窗口上添加更多东西来构建对话框。

示例

在本例中,我们创建了一个模态对话框,它有两个部分,

  • 初始化Toplevel窗口。
  • 弹出对话框事件的函数定义。
  • 在Toplevel窗口中添加小部件。
  • 对话框选项的函数定义。
# 导入所需的库
from tkinter import *
from tkinter import ttk

# 创建tkinter框架的实例
win = Tk()

# 设置窗口大小
win.geometry("700x350")
style = ttk.Style()
style.theme_use('clam')

# 定义实现选择函数的函数
def choice(option):
   pop.destroy()
   if option == "yes":
      label.config(text="你好,你怎么样?")
   else:
      label.config(text="你已经选择了No")
      win.destroy()
def click_fun():
   global pop
   pop = Toplevel(win)
   pop.title("确认")
   pop.geometry("300x150")
   pop.config(bg="white")
   # 创建一个标签文本
   label = Label(pop, text="您想继续吗?",
   font=('Aerial', 12))
   label.pack(pady=20)
   # 添加框架
   frame = Frame(pop, bg="gray71")
   frame.pack(pady=10)
   # 添加按钮进行选择
   button1 = Button(frame, text="是", command=lambda: choice("yes"), bg="blue", fg="white")
   button1.grid(row=0, column=1)
   button2 = Button(frame, text="否", command=lambda: choice("no"), bg="blue", fg="white")
   button2.grid(row=0, column=2)
# 创建一个标签小部件
label = Label(win, text="", font=('Aerial', 14))
label.pack(pady=40)

# 创建一个Tkinter按钮
ttk.Button(win, text="点击这里", command=click_fun).pack()

win.mainloop()

输出

运行上面的代码时,它将显示一个带有按钮的窗口,以打开模态对话框框。

如何在tkinter中创建模态对话框?

单击按钮将打开模态对话框框。

如何在tkinter中创建模态对话框?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程