我一直得到这个AttributeError:“\u tkinter.tkapp”对象没有属性“TK”

2024-07-04 07:44:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在做一个Gui多窗口任务,但Tkinter似乎没有Tk。我的全部错误是

Traceback (most recent call last):
  File "/Users/connorsmacbook/PycharmProjects/2.8/2.8 Internal/TextTypers 2.2.py", line 6, in <module>
    class TextTypers(tk.TK):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 2101, in __getattr__
    return getattr(self.tk, attr)
AttributeError: '_tkinter.tkapp' object has no attribute 'TK'

我的代码是

from tkinter import *
tk=Tk()

# Classes
class TextTypers(tk.TK):

    def __init__(self, *args, **kwargs): # Runs when our class is called and allows almost anything to be passed

        tk.Tk.__init__(self, *args, **kwargs)  # Initialise Tk
        window = tk.Frame(self)  # Creates the container the windows/frames will populate
        window.pack()

        self.frames = {}  # Creates a dictionary for the frames

        frame = MenuScreen(window, self)
        self.frames[MenuScreen] = frame
        frame.grid(row=0, column=0, sticky="nswe")
        self.show_frame(MenuScreen)  # Shows the menu screen as this is initialising

    def show_frame(self, cont):

        frame = self.frames[cont]  # Grabs value of self.frames and puts in in frame
        frame.tkraise()  # Raises frame to the front

class MenuScreen(tk.frame): # Inherits everything from the frame

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent) # Inherits from main class
        label = tk.Label(self, text="Menu")
        label.pack()

run = TextTypers()
run.mainloop()

如果有巫师能帮忙,我将不胜感激:)


Tags: theinfromselfframesinittkinterdef
1条回答
网友
1楼 · 发布于 2024-07-04 07:44:55

线路

tk=Tk()

创建名为Tk的Tk()实例

创建类时

class TextTypers(tk.TK):

您正试图从实例TK继承一个名为TK的属性

一般来说,我不会为根窗口使用名称tk,因为tk通常用作tkinter模块的别名

我想你想要的是这样的:

import tkinter as tk

# Classes
class TextTypers(tk.Tk):

    def __init__(self, *args, **kwargs): # Runs when our class is called and allows almost anything to be passed

        tk.Tk.__init__(self, *args, **kwargs)  # Initialise Tk
        window = tk.Frame(self)  # Creates the container the windows/frames will populate
        window.pack()

        self.frames = {}  # Creates a dictionary for the frames

        frame = MenuScreen(window, self)
        self.frames[MenuScreen] = frame
        frame.grid(row=0, column=0, sticky="nswe")
        self.show_frame(MenuScreen)  # Shows the menu screen as this is initialising

    def show_frame(self, cont):

        frame = self.frames[cont]  # Grabs value of self.frames and puts in in frame
        frame.tkraise()  # Raises frame to the front

class MenuScreen(tk.Frame): # Inherits everything from the frame

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent) # Inherits from main class
        label = tk.Label(self, text="Menu")
        label.pack()

run = TextTypers()
run.mainloop()

看看{a1}你可以找到一些建议和讨论

相关问题 更多 >

    热门问题