首页 > 解决方案 > 如何在定义的代码中编辑变量?

问题描述

该程序不会将 +1 添加到“总计”。有没有更好的编程方法?我也主要使用可能的 Pycharm。

from tkinter import * #imports tkinter

window = Tk() #Tk name

window.title("Cookie Clicker")#window title

window.geometry('350x200')#window size

lbl = Label(window, text="$0.00")#makes label

lbl.grid(column=0, row=0)#makes label

x=0  #possibly a problem
total=0 #possibly a problem

def clicked():  
    total = total+1  # also possibly causing problems
    lbl.configure(text='${:,.2f}'.format(total))#This is possibly causing problems 

btn = Button(window, text="Cookie", command=clicked)#This is the button

btn.grid(column=1, row=0)

mainloop()

标签: python-3.xtkinter

解决方案


问题是该变量total未在函数中定义。您可以通过创建total一个全局变量来解决此问题:

def clicked():
    global total  
    total = total+1
    lbl.configure(text='${:,.2f}'.format(total)) 

这会产生total一个全局变量,这意味着该函数可以在全局命名空间中更改它的值。您需要global在希望能够访问变量的每个函数中使用。

另一种解决方案是使用面向对象的方法并制作total属性。


推荐阅读