简体   繁体   English

如何使用 Tkinter 刷新 python 中的 label

[英]How do i refresh the label in python with Tkinter

i'm pretty new to python and i just created a small code to make sort of a click counter with the interface being made in Tkinter.我对 python 很陌生,我刚刚创建了一个小代码来制作一个点击计数器,界面是在 Tkinter 中制作的。 My problem is that each time i press the button with the coin it adds 1 to the coin counter underneath, that's what it is supposed to do but for some reason it can add 1 coin only once, after clicking the first time it doesn't work anymore, clicking the button does nothing.我的问题是,每次我用硬币按下按钮时,它都会在下面的硬币计数器上加 1,这就是它应该做的,但由于某种原因,它只能添加 1 个硬币,在第一次点击后它不会工作了,点击按钮什么都不做。 I appreciate any help.我很感激任何帮助。

from tkinter import *

window=Tk()

window.maxsize(800,800)
window.minsize(800,800)
window.title("coins")
window.iconbitmap("coin.ico")
window.config(background="#7693c2")

coin = 0

def addcoin():
    coin =+ 1
    label.config(text=coin)


frame1 = Frame(window,bg="#7693c3")
frame2 = Frame(window,bg="#7693c2")

CoinImage = PhotoImage(file="coin.png").zoom(10).subsample(13)
CoinImage2 = PhotoImage(file="coin.png").zoom(10).subsample(60)

AddCoinButton = Button(frame1, borderwidth= 30, image=CoinImage, bg="#93aacf", command=addcoin)
AddCoinButton.grid(column= 0, row=0 ,padx=180,pady=40)

canvas = Canvas(frame2, width = 100, height= 100, bg="#7693c2", bd=0, highlightthickness=0 )
canvas.create_image(50,50, image = CoinImage2)
canvas.grid(column=0,row=0)

label = Label(frame2, text=coin,bg="#7693c2",font=("ASI_System",50))
label.grid(column=1,row=0)


frame1.grid(column=0,row=0)
frame2.grid(padx=300,column=0,row=1,sticky="w")

window.mainloop()

There are two issues with your code.您的代码有两个问题。 First, you have a typo in addcoin() , the augmented addition operator is += , not =+ .首先,您在addcoin()中有一个错字,增广加法运算符是+= ,而不是=+ Your code is assigning the value +1 every time.您的代码每次都分配值+1

Second, the coin variable you defined is a global one (defined at the top level, outside any 'def' scope), but when you try to access coin inside the addcoin() function, python assumes you want a local variable, and it will complain that it's being referenced before assignment.其次,您定义的coin变量是一个全局变量(在顶层定义,在任何“def”范围之外),但是当您尝试在addcoin() function、python 中访问coin时,假设您需要一个局部变量,并且它会抱怨它在分配之前被引用。 To tell python that you want the global variable, use the global statement.要告诉 python 您想要全局变量,请使用global语句。

You can change you addcoin function like this:您可以像这样更改您的 addcoin function:

def addcoin():
    global coin
    coin += 1
    label.config(text=coin)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM