【问题标题】:main() creates undefined error when running starter filemain() 在运行启动文件时创建未定义的错误
【发布时间】:2021-03-25 09:51:59
【问题描述】:

我将使用我的导师提供给我的这个起始文件来编写一个程序。问题是她给我们的文件没有运行。我不知道这是因为我使用的是 IDLE,还是代码只在某些操作系统上运行。

例如,我使用 Windows,但我的老师同时使用 Windows 和 Linux 系统。我无法让她弄清楚这个问题,所以我希望你们能。

目前,当我运行启动文件时,出现错误:

TypeError: main() is not defined.

当我在程序底部将main() 切换为GUI() 时,出现新错误:

TypeError: __init__() missing 1 required positional argument: 'rootWindow'

这是完整的代码:

from tkinter import*
from tkinter import tk

class GUI:
    def __init__(self,rootWindow):
        self.label = ttk.Label(rootWindow, text="Hellow World!")
        self.label.grid(row=0,column=0)

        self.button1=ttk.Button(rootWindow,text="Hello",command=self.hello)
        self.button1.grid(row=0,column=1)
        self.button2=ttk.Button(rootWindow,text="Bye",command=self.bye)
        self.button2.grid(row=0,column=2)

    def bye(self):
        self.label.config(text="GoodbyeWorld!")

    def hello(self):
        self.label.config(text="HelloWorld!")

    def main():
        global label
        rootWindow = Tk()

        gui = GUI(rootWindow)
        rootWindow.mainloop()

main()

【问题讨论】:

  • GUI() 需要 rootWindow 参数。
  • main 未定义。 GUI.main 是。

标签: python python-3.x class tkinter main


【解决方案1】:

这段代码有两个问题:

  1. 您需要取消缩进main 函数,否则您不能只调用main,因为它是GUI 类的一部分。

  2. 导入搞砸了。您需要import tkinter as ttk,否则ttk 是未定义的,并且import Tk 而不是import tk

请注意,我使用的是 Python 3,因此如果您使用的是 Python 2,您的可能会略有不同。

完整的更正代码如下:

import tkinter as ttk
from tkinter import Tk

class GUI:
    def __init__(self,rootWindow):
        self.label = ttk.Label(rootWindow, text="Hellow World!")
        self.label.grid(row=0,column=0)

        self.button1=ttk.Button(rootWindow,text="Hello",command=self.hello)
        self.button1.grid(row=0,column=1)
        self.button2=ttk.Button(rootWindow,text="Bye",command=self.bye)
        self.button2.grid(row=0,column=2)

    def bye(self):
        self.label.config(text="GoodbyeWorld!")

    def hello(self):
        self.label.config(text="HelloWorld!")

def main():
    global label
    rootWindow = Tk()

    gui = GUI(rootWindow)
    rootWindow.mainloop()

main()

【讨论】:

  • 我现在明白了,这很有意义,并且对运行启动文件有很大帮助!非常感谢!
猜你喜欢
  • 2016-08-03
  • 1970-01-01
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-15
  • 2013-07-12
  • 1970-01-01
相关资源
最近更新 更多