0

当我尝试基于示例 Tkinter GUI 运行我的程序时,没有任何反应。我还是 Pydev 的新手,但我觉得这很不寻常。我有一个包含代码的 Main.py 文件,我尝试简单地运行该模块而没有任何成功。

我只是从这个参考中复制/粘贴,

# Main.py
import tkinter as tk;

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.hi_there = tk.Button(self)
        self.hi_there["text"] = "Hello World\n(click me)"
        self.hi_there["command"] = self.say_hi
        self.hi_there.pack(side="top")

        self.quit = tk.Button(self, text="QUIT", fg="red",
                              command=root.destroy)
        self.quit.pack(side="bottom")

    def say_hi(self):
        print("hi there, everyone!")

root = tk.Tk()
app = Application(master=root)
app.mainloop()

运行该模块的唯一结果是专用于 Main.py 的空 Liclipse 控制台。我还尝试了其他站点的其他示例,但没有运气。另外,如果重要的话,我目前正在使用 MacOS。

4

1 回答 1

0

您确定在 Liclipse 中正确配置了所有内容(工作目录、python 路径...)吗?我刚刚尝试了全新安装,在将 Liclipse 配置为在 Python 3.6 中运行当前项目并选择主项目文件作为此源代码后,它会按预期运行并显示一个带有按钮的窗口,并且它也将文本打印到控制台。

此外,以这种方式初始化按钮感觉不是很“pythonic”。我宁愿这样建议:

# Main.py
import tkinter as tk;

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        mytext = "Hello World\n(click me)"
        self.hi_there = tk.Button(self, text=mytext, command=self.say_hi)
        self.hi_there.pack(side="top")

        self.quit = tk.Button(self, text="QUIT", fg="red", command=root.destroy)
        self.quit.pack(side="bottom")

    def say_hi(self):
        print("hi there, everyone!")

root = tk.Tk()
app = Application(master=root)
app.mainloop()

该代码看起来更具可读性并且以相同的方式工作。当你开始扩展你的界面时,它会有很多行,通过在每个按钮上减少两行,你可以让它更短。我一直在用超过 1500 行代码编写一个 tkinter 应用程序,那时我向自己保证,我会尝试学习如何让它更有条理和简短;)

于 2017-04-20T15:06:35.817 回答