如何修复 simpledialog tkinter 中的错误窗口路径名错误?
python 288
原文标题 :How to fix bad window path name error in simpledialog tkinter?
考虑到一个继承自tk.Tk
的类的基本应用程序,我在使用simpledialog
模块 fromtkinter
时收到意外错误消息。它与覆盖此类中的__str__
方法有关,因为simpledialog
确实可以在没有字符串覆盖的情况下工作,所以我的猜测是simpledialog
期望那里的默认行为。请参阅下面的错误消息:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\**\Python39\lib\tkinter\__init__.py", line 1884, in __call__
return self.func(*args)
File "C:\**\bad_window_error.py", line 22, in start_dialog
result = simpledialog.askstring('Simple dialog', 'Fill in a string..')
File "C:\**\Python39\lib\tkinter\simpledialog.py", line 399, in askstring
d = _QueryString(title, prompt, **kw)
File "C:\**\Python39\lib\tkinter\simpledialog.py", line 376, in __init__
_QueryDialog.__init__(self, *args, **kw)
File "C:**\Python39\lib\tkinter\simpledialog.py", line 271, in __init__
Dialog.__init__(self, parent, title)
File "C:\**\Python39\lib\tkinter\simpledialog.py", line 138, in __init__
self.transient(parent)
File "C:\**\Python39\lib\tkinter\__init__.py", line 2225, in wm_transient
return self.tk.call('wm', 'transient', self._w, master)
_tkinter.TclError: bad window path name "random"
我整理了一个最小的例子,见下文。我正在处理的实际代码要大得多,有很多依赖项,到目前为止,我只注意到simpledialog
模块发生了这个错误。
import tkinter as tk
from tkinter import ttk
from tkinter import simpledialog, messagebox
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title('Random app')
self.option_add('*tearOff', False)
self.start_dialog_button = ttk.Button(self, text='Run simple dialog', command=self.start_dialog)
self.start_dialog_button.grid(row=0, column=0, sticky='nesw')
def __str__(self):
return "random"
@staticmethod
def start_dialog():
messagebox.showinfo('hello', 'this works')
result = simpledialog.askstring('Simple dialog', 'Fill in a string..')
messagebox.showinfo('Result', result)
if __name__ == '__main__':
app = App()
app.mainloop()
如果字符串覆盖被注释掉,代码应该按预期运行。有没有办法在使用simpledialog
模块的同时仍然覆盖tk.Tk
的默认__str__
方法或者我不应该这样做?
回复
我来回复-
Ran A 评论
最好不要覆盖默认功能;如果您希望这样做来更改输出结果,则可以轻松完成,而不会产生额外的问题。
@staticmethod def start_dialog(): messagebox.showinfo('hello', 'this works') result = simpledialog.askstring('Simple dialog', 'Fill in a string..') if (result is None or result == '') : result="random" else: result=result+" this should work" messagebox.showinfo('Result', result)
2年前