[英]issue with tkinter and variables
当我运行这个时,我收到一个我不明白的错误
我曾尝试编辑变量来解决这个问题,但它没有奏效
from tkinter import *
cookie = 0
am = 1
def cookieFunc():
global cookie
global am
cookie = cookie + am
print(cookie)
def grandma():
global cookie
global am
if cookie >= 10:
cookie = cookie - 10
am = am + 0.5
def farm():
global cookie
global am
if cookie >= 100:
cookie = cookie - 100
am = am + 5
root = Tk()
root.geometry('300x300')
cookie = Button(root, text='cookie', command=cookieFunc)
cookie.pack()
grandma = Button(root, text='grandma', command=grandma)
grandma.pack()
farm = Button(root, text='farm', command=farm)
farm.pack()
root.mainloop()
当您单击 cookie 时,它应该向 cookie 中添加 1 应该向 am 中添加 0.5,这是您每次点击农场获得的 cookie 数量应该向 am 中添加 5
您有问题,因为您对不同的变量使用相同的名称
cookie = 0
cookie = Button(...)
所以你认为你添加了两个整数
cookie + am
但是 Python 看到了
Button + am
与......类似
def farm()
farm = Button(...)
def grandma()
grandma = Button(...)
工作代码使用button_cookie
, button_farm
from tkinter import *
cookie = 0
am = 1
def cookieFunc():
global cookie
global am
cookie = cookie + am
print(cookie, am)
def grandma():
global cookie
global am
if cookie >= 10:
cookie = cookie - 10
am = am + 0.5
print(cookie, am)
def farm():
global cookie
global am
if cookie >= 100:
cookie = cookie - 100
am = am + 5
print(cookie, am)
root = Tk()
root.geometry('300x300')
button_cookie = Button(root, text='cookie', command=cookieFunc)
button_cookie.pack()
button_grandma = Button(root, text='grandma', command=grandma)
button_grandma.pack()
button_farm = Button(root, text='farm', command=farm)
button_farm.pack()
root.mainloop()
一开始你声明了 int 变量cookie
:
cookie = 0
之后,您将Button()
分配给此变量:
cookie = Button(root, text='cookie', command=cookieFunc)
我想,这不是你想做的。 只需重命名变量之一。
PS 尝试使用 IDE,它会突出显示被阴影的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.