python-3.x - 如何在定义的代码中编辑变量?
问题描述
该程序不会将 +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()
解决方案
问题是该变量total
未在函数中定义。您可以通过创建total
一个全局变量来解决此问题:
def clicked():
global total
total = total+1
lbl.configure(text='${:,.2f}'.format(total))
这会产生total
一个全局变量,这意味着该函数可以在全局命名空间中更改它的值。您需要global
在希望能够访问变量的每个函数中使用。
另一种解决方案是使用面向对象的方法并制作total
属性。
推荐阅读
- mysql - Mysql 选择最大连续记录(有间隙)
- python - python中如何通过对特征值进行排序来快速改变对应的特征向量?
- c# - Xamarin 连通性变化变换函数
- angular - 如何从 url 获取令牌的值并将其分配给输入值
- amazon-dynamodb - 为什么 DynamoDB 不支持索引/表重命名?
- ionic-framework - 如何在 Ionic 中将 base64 字符串转换为 JPG 或 Png
- mysql - MYSQL查询每周获取新客户
- java - 使用java查找数组中的第二大值?
- python - 如何更改模型中日期字段的格式?
- wpf - 获取模板中内容的实际大小以绘制不规则形状的按钮