在使用 Python tkinter 创建图形用户界面时,可能遇到以下错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
return self.func(*args)
File "C:\Users\Eduard\Desktop\Zeugs\python\test.py", line 69, in ok3
label['text']=random.choice(WORDS)
File "C:\Python33\lib\random.py", line 249, in choice
i = self._randbelow(len(seq))
TypeError: object of type 'NoneType' has no len()
这个错误通常是由变量 WORDS
未正确初始化引起的。变量 WORDS
应该是包含单词列表的元组或字符串。
2、解决方案:
要解决此错误,请执行以下步骤:
- 检查变量
WORDS
是否正确初始化。确保它包含一个字符串或元组,其中包含您想要在标签中随机选择的单词列表。 - 如果变量
WORDS
是从用户输入中获取的,请确保它已经正确处理过,并且不包含任何特殊字符或空格。 - 如果变量
WORDS
仍然为空,请尝试使用其他方法来填充它。例如,您可以使用open()
函数从文本文件中读取单词列表,或使用random.choice()
函数从内置的单词列表中随机选择一个单词。
以下是一段经过修复的代码片段:
import tkinter as tk
from tkinter import *
import random
from functools import partial
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container= tk.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 (mode2, scale1):
frame= F(container, self)
self.frames[F]=frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(mode2)
def show_frame(self, c):
frame=self.frames[c]
frame.tkraise()
class mode2(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
def antmenge(self):
label1["text"]="Mögliche Antworten: " \
+ str(antmengen.get()) + " "
label1=tk.Label(self, text="Mögliche Antworten: 0 Wörter", width=25)
label1.pack()
antmengen=IntVar()
antmengen.set(0)
antm=Scale(self, width=20, length=200, orient="vertical", from_=0, to=20,
resolution=1, tickinterval=10, label="Wörter", command=antmenge(self),
variable=antmengen)
antm.pack()
def abfrage():
if antmengen.get()==1:
button3=Button(self, text="push again", command=lambda: controller.show_frame(scale1))
button3.pack()
button2=tk.Button(self, text="push", command=abfrage)
button2.pack()
class scale1(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label1=Label(self, text="Wort1")
label1.pack()
wort1auf=Entry(self)
wort1auf.pack()
label=tk.Label(self, text=" ")
label.pack()
def ok3(label):
WORDS = ("Apfel", "Birne", " Kirsche")
label['text']=random.choice(WORDS)
button1=tk.Button(self, text="push", command=partial(ok3, label))
button1.pack()
if __name__== "__main__":
app=SampleApp()
app.mainloop()
此代码中,变量 WORDS
已初始化为包含三个单词的元组,并且无需再从用户输入中获取。这样就可以避免对象长度错误,确保代码能够正常运行。