Tkinter和变量的问题

时间:2019-07-11 11:18:37

标签: python python-3.x tkinter

运行此命令时,出现我不理解的错误

我尝试编辑变量来解决该问题,但没有成功

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 奶奶应该在上午添加0.5,这是您每次点击获得的Cookie数量 农场应加5上午

2 个答案:

答案 0 :(得分:2)

您遇到了问题,因为您对不同的变量使用了相同的名称

cookie = 0
cookie = Button(...)

所以您认为您在

中添加了两个整数
cookie + am

但Python请参见

Button + am

类似于

def farm()
farm = Button(...)

def grandma()
grandma = Button(...)

工作代码使用button_cookiebutton_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()

答案 1 :(得分:1)

在开始时,您声明了int变量cookie

cookie = 0

之后,您将Button()分配给此变量:

cookie = Button(root, text='cookie', command=cookieFunc)

我认为,这不是您想要做的。 只需重命名变量之一。

P.S。尝试使用IDE,它将突出显示已被阴影覆盖的变量。