【问题标题】:Tkinter inherited class not behaving properly on UbuntuTkinter 继承的类在 Ubuntu 上无法正常运行
【发布时间】:2018-10-14 23:08:50
【问题描述】:

我创建了一个直接从根窗口继承的简单类,它可以在 Mac 机器上完美运行。但是,当我尝试在我自己的基于 Ubuntu 的机器上运行它时,它会因以下错误而崩溃。这是什么原因造成的?

Traceback (most recent call last):
  File "/home/estilen/Dropbox/Python/email_viewer/dialog.py", line 15, in <module>
    Dialog('This is definitely working')
  File "/home/estilen/Dropbox/Python/email_viewer/dialog.py", line 7, in __init__
    tk.Tk.__init__(self, dialog_message)
  File "/usr/lib/python3.5/tkinter/__init__.py", line 1871, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: couldn't connect to display "This is definitely working"

代码:

import tkinter as tk


class Dialog(tk.Tk):

    def __init__(self, dialog_message):
        tk.Tk.__init__(self, dialog_message)
        self.geometry('400x100')
        label = tk.Label(self, text=dialog_message)
        label.pack(anchor='center', side='top', pady=10)
        self.mainloop()


if __name__ == '__main__':
    Dialog('This is definitely working')

【问题讨论】:

  • 尝试将__init__的第一行改成下面的tk.Tk.__init__(self, className=dialog_message)

标签: python oop tkinter


【解决方案1】:
tk.Tk.__init__(self, dialog_message)

这对我来说看起来不对。 Tk 构造函数的第一个位置参数是screenName。如果您不想在名为“这绝对有效”的显示器上显示您的窗口,请不要提供该参数。

tk.Tk.__init__(self)

...或者,更惯用的说法,

super().__init__()

【讨论】:

  • 我的实现如何在 Mac 机器上运行?
  • @LukaszSalitra 我觉得这个论点由于某种原因被忽略了。
  • 我怀疑如果操作系统不支持命名显示,它会简单地忽略该参数。如果 Mac 不支持命名显示器,那就可以解释了
  • @Kevin 有道理。谢谢。
猜你喜欢
  • 2020-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多