gpt4 book ai didi

python - AttributeError: 'Application' 对象没有属性 'tk'

转载 作者:行者123 更新时间:2023-11-30 22:15:37 25 4
gpt4 key购买 nike

我有以下脚本,它使用 Tkinter:

import tkinter as tk

class Application(tk.Frame):

def __init__(self, master):
frame = tk.Frame(master)
frame.pack

self.PRINT = tk.Button(frame, text = 'Print', fg = 'Red', command = self.Print())
self.PRINT.pack(side = 'left')

self.QUIT = tk.Button(frame, text = 'Quit', fg = 'Red', command = self.quit())
self.QUIT.pack(side = 'left')

def Print(self):
print('at least somethings working')

root = tk.Tk()

b = Application(root)
root.mainloop()

当我运行它时,出现以下错误:

AttributeError: 'Application' object has no attribute 'tk'

为什么我会收到此错误?

最佳答案

我在这里运行了你的脚本并得到了这个堆栈跟踪:

Traceback (most recent call last):
File "t.py", line 23, in <module>
b = Application(root)
File "t.py", line 15, in __init__
self.QUIT = tk.Button(frame, text = 'Quit', fg = 'Red', command = self.quit())
File "/usr/lib/python3.6/tkinter/__init__.py", line 1283, in quit
self.tk.quit()
AttributeError: 'Application' object has no attribute 'tk'

错误消息出现在最后,但整个堆栈很重要!我们来分析一下。

显然,有一个对象,Application 的实例类,没有 tk属性。有道理:我们创建了这个类,但没有添加这个属性。

好吧,主循环期望存在一个属性!发生的事情是,我们的类(class)扩展了tkinter.Frame ,框架需要这个 tk属性。幸运的是,我们不必考虑如何创建它:由于所有框架都需要它,框架初始值设定项(其 __init__() 方法)知道如何设置此属性。

那么,我们要做的就是调用 tkinter.Frame我们自己的初始化器中的初始化器。这可以通过调用 __init__() 轻松完成。直接来自tk.Frame ,通过self变量:

tk.Frame.__init__(self, master)

整个脚本将是这样的,然后:

import tkinter as tk

class Application(tk.Frame):

def __init__(self, master):
tk.Frame.__init__(self, master)

frame = tk.Frame(master)
frame.pack

self.PRINT = tk.Button(frame, text = 'Print', fg = 'Red', command = self.Print())
self.PRINT.pack(side = 'left')

self.QUIT = tk.Button(frame, text = 'Quit', fg = 'Red', command = self.quit())
self.QUIT.pack(side = 'left')

def Print(self):
print('at least somethings working')

root = tk.Tk()

b = Application(root)
root.mainloop()

现在,您的脚本中还会有一些其他错误,您很快就会发现;)还有一些与多重继承相关的复杂问题可以解决 with the super() function 。尽管如此,这是您的第一个错误的解决方案。

关于python - AttributeError: 'Application' 对象没有属性 'tk',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50222747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com