python-3.x - 在标签中显示随机选择项目的次数
问题描述
我的 label2 应该显示每个项目(这里是苹果)出现的次数也就是说,如果选择了苹果,我的计数器(label2)应该显示 1 然后 2、3 .. 但它似乎不起作用。
from tkinter import*
import random, time
wn=Tk()
wn.geometry("300x300")
mytext=Text(wn,bg="pink",width=10,height=200)
mytext.pack()
label1=Label(wn,text="",bg="yellow",bd=3)
label1.place(x=200,y=20)
label2=Label(wn,text="",bg="lightgreen",bd=3)
label2.place(x=200,y=50)
def update(c=0):
numx = 0
list1=["apple","orange","melon","carrot"]
fruit = random.choice(list1)
label1["text"]=fruit
if label1["text"]=="apple":
numx+=1
label2["text"]=numx
mytext.insert('end', str(fruit) + '\n')
wn.after(1000, update, c+1)
update()
wn.mainloop()
解决方案
每次调用您定义numx
为零。update
首先移出numx
你的update
函数,然后global
在里面声明update
:
from tkinter import*
import random, time
wn=Tk()
...
numx = 0
def update(c=0):
global numx
...
update()
wn.mainloop()
推荐阅读
- c# - 将 json 反序列化为列表时的空指针
- android - 如何在协调器布局中添加拉动刷新
- node.js - facebook graph api:将别人的页面订阅到我的应用程序
- php - count():参数必须是数组或对象,在 Laravel 6 中实现了 Countable
- xml - 在 XML 负载中查找不同的值 | XSL 映射| SOA|BPEL
- c# - 如何访问 Hashtable list/Viewmode.Model 中的值并在 View 中显示?
- db2 - 如何在 DB2 10.5 及更高版本中找到最旧的活动事务?
- reactjs - 自定义 GroupRow 渲染 (mbrn/MaterialTable) React
- oracle - 全局临时表空间分配是否发生在会话开始?
- javascript - 移动菜单样式以显示活动菜单