【发布时间】:2019-05-10 23:56:37
【问题描述】:
我正在为我的程序使用this 帖子中的这些日历模块,并对导入进行了一些细微的修改以使其适用于最新的 python 版本。
我将只显示我认为对这个问题很重要的代码的 sn-ps。
所以我制作了这个用于警报的弹出窗口:
#class for pop-up windows for alerts, errors etc.
class PopUpAlert():
def __init__(self, alert='Alert!'):
self.root = tk.Tk()
tk.Label(self.root,
text=alert,
font="Verdana 15",
fg='red',
padx=10,
pady=5).pack(side=tk.TOP)
self.root.bind('<Return>', (lambda event: self.ok()))
tk.Button(self.root,
text='ok',
pady=10,
command=self.ok).pack(side=tk.TOP)
def ok(self):
print('ok clicked')
self.root.destroy()
函数ok 只是为了测试该函数是否被调用。这个窗口在我的代码中工作得很好,除了当我尝试使用日历实现时,我的PopUpAlert 的“确定”按钮(应该破坏窗口)停止工作:
class CalendarDialog(tkSimpleDialog.Dialog):
"""Dialog box that displays a calendar and returns the selected date"""
def body(self, master):
self.calendar = ttkcalendar.Calendar(master)
self.calendar.pack()
def apply(self):
self.result = self.calendar.selection
def validate(self):
if self.calendar.selection == None:
PopUpAlert(alert='Please select a date or click cancel!')
return False
return True
日历有一个“确定”按钮,用于确认选择日期并关闭日历窗口。我试图做的是使用户无法单击“确定”以关闭窗口,如果他/她没有选择日期。为此,我使用了函数validate,它是在tkSimpleDialog.Dialog 类中预定义的,我的CalendarDialog 继承自该类。我重写了CalendarDialog 类中的函数以调用PopUpAlert,然后将False 返回给父函数ok(在日历窗口上按下“确定”按钮时调用):
def ok(self, event=None):
if not self.validate():
self.initial_focus.focus_set() # put focus back
return
self.withdraw()
self.update_idletasks()
self.apply()
self.cancel()
def cancel(self, event=None):
# put focus back to the parent window
self.parent.focus_set()
self.destroy()
(整个内容可以在我上面链接的另一个 SO 页面中链接的 tkSimpleDialog 文件中找到。)
在逐行注释掉之后,我发现我的PopUpAlert 上的“确定”按钮只有在日历上没有调用self.root.destroy() 时才不起作用。为什么?我该如何解决这个问题?
我已经尝试将我的 PopUpAlert 更改为 Toplevel 窗口,但也没有用。
【问题讨论】:
-
看起来您在代码中不止一次调用
Tk()。那永远不会结局好... -
@jasonharper 我说我已经尝试过使用 toplevel 代替
标签: python-3.x tkinter