【问题标题】:Why does Python say that 'App' is not defined when I use Tkinter?为什么 Python 说我使用 Tkinter 时没有定义“应用程序”?
【发布时间】:2018-12-22 03:43:34
【问题描述】:

我正在尝试为一个学校项目创建一个 GUI,但它一直说 Tkinter 的强制性步骤之一没有定义。

我已经导入了 Tkinter,顺便说一句。

这是我的代码:

from tkinter import *

app = App()


class App(Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init(self, *args, **kwargs)
        container = Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (StartPage, CoachPick):
            frame = F(self, container)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, context):
        frame = self.frames[context]
        frame.tkraise()


class StartPage(Frame):

    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        text = Label(self, text="Hello. Welcome to the Basketball Game. In this game, you will be trying to draft a team.", fg="black")
        text2 = Label(self, text="As you go on, more directions will be given to you. Enjoy!", fg="black")

        text.pack()
        text2.pack()

        button = Button(self, text="Start", bg="white", fg="black", command=lambda: controller.show_frame(CoachPick))
        button.pack()


def printTextSteve():


    print("Your coach is Steve Kerr.")



def printTextGregg():


    print("Your coach is Gregg Poppovich.")



def printTextBrad():


    print("Your coach is Brad Stevens.")



class CoachPick(Frame):

    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        text3 = Label(self, text="The first thing you need to do pick a coach. You will have 3 options:", fg="black")
        text3.pack()

        button2 = Button(self, text="Steve Kerr", bg="white", fg="red", command=printTextSteve)
        button2.pack()
        button3 = Button(self, text="Gregg Poppovich", bg="white", fg="red", command=printTextGregg)
        button3.pack()
        button4 = Button(self, text="Brad Stevens", bg="white", fg="red", command=printTextBrad)
        button4.pack()


app.mainloop()

我的问题:

它表示未定义名称“App”。为什么?

【问题讨论】:

  • 请问回溯是什么?
  • 另外,我已经编辑了你的代码,但现在看起来你有一个嵌套类。是我弄错了还是你原来的代码?
  • 你需要在类定义后面加上app = App()...

标签: python user-interface tkinter


【解决方案1】:

在创建类之前调用​​它。将 App 类放在 app = App() 行上方。

【讨论】:

  • app = App() 放在app.mainloop() 之前会更好读。
猜你喜欢
  • 2018-08-21
  • 2016-09-19
  • 2020-08-25
  • 1970-01-01
  • 1970-01-01
  • 2015-06-26
  • 1970-01-01
  • 1970-01-01
  • 2017-08-29
相关资源
最近更新 更多