【发布时间】:2017-11-27 03:51:45
【问题描述】:
我做了一个程序,但无缘无故,除了第 4 次之外,每次都会引发类似于此无法解释的错误的错误:
Traceback (most recent call last):
File "C:\Users\caleb.sim\3D Objects\Sim Inc\Applications\Games\Chicken Clicker\class1.py", line 54, in <module>
openbutton = Button(root, image=photo, width = 500, height=500, command = moar_eggz)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2165, in __init__
Widget.__init__(self, master, 'button', cnf, kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2095, in __init__
(widgetName, self._w) + extra + self._options(cnf))
TclError: unknown color name ".45051576"
我无法理解错误。如果它有帮助,就像通常那样,这里是代码:
from tkinter import *
from PIL import Image, ImageTk
import time, threading
root = Tk()
root.title("Chicken Clicker")
eggz = 0
eggvalue = 0.2
eggzps = 0
chookz = 0
def moar_eggz():
global eggz, eggvalue, eggzps, chookz
chookz = chookz + 1
eggzps = chookz / 100
printchookz = round(chookz)
def update_labels():
try:
while True:
eggzLabel = "Eggs: " + str(eggz)
eggzpsLabel = eggzps
eggvalueLabel = "Egg Value: " + str(eggvalue)
chookzLabel = " Chickens: " + str(chookz)
label1.config (text=eggzLabel)
label2.config (text=eggzpsLabel)
label3.config (text=eggvalueLabel)
label4.config (text=chookzLabel)
time.sleep(0.2)
except: pass
def main_loop():
global eggz, printeggzps
try:
while True:
global eggz, printeggzps
eggz += printeggzps
time.sleep(1)
except: pass
eggzLabel = "Eggs: " + str(eggz)
eggzpsLabel = eggzps
eggvalueLabel = "Egg Value: " + str(eggvalue)
chookzLabel = " Chickens: " + str(chookz)
label4 = Label(root, text=eggzLabel)
label3 = Label(root, text=eggzLabel)
label2 = Label(root, text=eggzLabel)
label1 = Label(root, text=eggzLabel)
label4.pack()
label3.pack()
label2.pack()
label1.pack()
imagecnv = Image.open("img\\1.png")
photo = ImageTk.PhotoImage(imagecnv)
threading.Thread (target = main_loop).start()
threading.Thread (target = update_labels).start()
openbutton = Button(root, image=photo, width = 500, height=500, command = moar_eggz)
openbutton.pack()
root.mainloop()
我不知道是什么原因造成的。
我们将不胜感激!
提前致谢!
【问题讨论】:
-
您能否提及您遇到此错误的操作系统。请看看这是否有帮助:bugzilla.redhat.com/show_bug.cgi?id=1043686
-
Tkinter 和线程相处得不是很好 - 你的线程运行
main_loop()应该不是问题,因为它不会触及任何 Tkinter 对象,但update_labels()绝对是一个问题.使用.after()安排未来的函数调用更有可能奏效。 -
最好使用
root.after(milliseconds, function)而不是线程,while循环和sleep() -
不要使用
except:pass,你不会看到你有错误。至少使用except Exception as e: print(e)。 -
你可以在
moar_eggz()中执行update_labels(),你不需要while和线程来运行这个函数。printeggzps是什么?它给出了错误。但是看不到,因为你用except:pass