我正在try 编写一个与askyesno()相同的自定义消息框(为更大的项目做准备),而Grab_Set()在用户 Select 按钮之前不会维护对程序的控制.如何让Grab_Set()在用户单击消息框中的按钮之前保持对程序流的控制,以及将用户的 Select 返回给调用函数的最佳方式是什么?
import tkinter as tk
from tkinter import Menu, ttk
from tkinter.messagebox import askyesno
class Test(tk.Tk):
def builtin(self, wtitle):
print('Button One')
answer = askyesno(title=wtitle, message='Click something', icon='info')
print('User pressed: %s' % answer)
def custom(self, wtitle):
print('Button Two')
answer = popup_msg(self, wtitle, 'Click to close')
print('User pressed: %s' % answer)
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.wm_title('Test')
self.geometry('300x100')
frame = ttk.Frame(self)
button_one = ttk.Button(self, text='Built-in',
command=lambda: self.builtin('Built-In'))
button_two = ttk.Button(self, text='Custom',
command=lambda: self.custom('Custom'))
button_one.pack(padx=5, pady=5)
button_two.pack(padx=5, pady=5)
frame.pack()
def popup_msg(root, wtitle, msg):
ret = False
def test_func(val):
popup.destroy()
return val
popup = tk.Toplevel()
popup.wm_title(wtitle)
popup.geometry("300x100")
label = ttk.Label(popup, text=msg, anchor=tk.CENTER)
label.pack(side="top", fill="x", pady=10)
button1 = ttk.Button(popup, text="Yes", command = lambda: test_func(True))
button2 = ttk.Button(popup, text="No", command = lambda: test_func(False))
button1.pack()
button2.pack()
popup.grab_set()
return ret
app = Test()
app.mainloop()
上面的代码创建了两个按钮-内置调用askyesno(),而Custom调用一个用于创建MessageBox的函数.内置函数打印出"Button One",然后显示消息框.当用户 Select 是或否时,该框消失,该功能打印用户的 Select .使用Custom时,该功能会打印"Button Two"和"User Press False",并打开自定义窗口.单击是或否关闭窗口,但对打印输出的内容没有影响.