如何修复 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__方法或者我不应该这样做?

原文链接:https://stackoverflow.com//questions/71599525/how-to-fix-bad-window-path-name-error-in-simpledialog-tkinter

回复

我来回复
  • Ran A的头像
    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年前 0条评论