首页 > 解决方案 > 在标签中显示随机选择项目的次数

问题描述

我的 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()

标签: python-3.xtkinter

解决方案


每次调用您定义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()

推荐阅读