gpt4 book ai didi

python - Tkinter 导入时出错

转载 作者:太空宇宙 更新时间:2023-11-03 18:54:46 24 4
gpt4 key购买 nike

我正在用 Python 2.7 编写 Tkinter 应用程序,但遇到了一些以前从未遇到过的麻烦。据我所知,Tkinter 模块似乎是为我的类中的 __init__ 函数导入的,但不是为其他函数导入的。这是我所得到的简化版本:

from Tkinter import *

class App:
def __init__(self):
self.master = Tk()
self.window = Frame(self.master)
self.window.grid()

self.BuildFrames()
self.master.mainloop()

def BuildFrames(self):
frames = []
frames.append(Frame(self.window,borderwidth=2,padx=10,pady=10))
# more code follows...

for Frame in frames:
Frame.grid()


App()

当我运行此程序时,出现以下错误:

Traceback (most recent call last):
File "myApp.py", line 131, in <module>
App()
File "myApp.py", line 12, in __init__
self.BuildFrames()
File "myApp.py", line 26, in BuildFrames
frame1 = Frame(self.window,borderwidth=2,padx=10,pady=10)
UnboundLocalError: local variable 'Frame' referenced before assignment

据我所知,Frame 函数在 BuildFrames() 函数中未被识别为 Tkinter 方法。它到底是如何在 __init__ 中被识别,但在 BuildFrames 中却不能被识别???

我可以通过将导入更改为来解决问题:

import Tkinter as Tk

然后在所有 Tkinter 方法前面添加一个 Tk. ,但宁愿避免它(无论如何我都不应该这样做!)

我肯定错过了导入工作方式的一些重要内容,但我可以发誓这种相同类型的代码以前对我有用。有人可以帮我解决这个问题吗?

最佳答案

也许在您的代码中的某个位置,Frame = ... 存在。将该变量重命名为 Frame 以外的名称。

您正在执行类似以下代码的操作:

>>> def f():
... a + 1
... a = 0
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local variable 'a' referenced before assignment

Why am I getting an UnboundLocalError when the variable has a value?

编辑

按如下方式更改您的 BuildFrame:

def BuildFrames(self):
frames = []
frames.append(Frame(self.window,borderwidth=2,padx=10,pady=10))
# more code follows...

for frame in frames:
frame.grid()

关于python - Tkinter 导入时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17520250/

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