How to update a label in python?

為{幸葍}努か 提交于 2019-12-12 04:12:28

问题


I'm new to python, and I was creating a small game when I got a problem. I searched for an answer, found one, yet it didn't work.

The game I'm trying to make is more or less a recreation of Cookie Clicker, and I'm trying to make the label which I have the score on update, instead, it creates a new label.

from tkinter import *
import time

master = Tk()

def uiPrint():
print("")
print(click)
blankLine()

click = 0
mult = 1
dcp1 = 0

def blankLine():
    for i in range(20):
        print("") 

def buttonCommand():
    global click
    global mult
    click += 1*(mult)
    uiPrint()
scoreCommand = Button(text=click)
scoreCommand.pack()

mainClickButton = Button(master, text="Click me!", command = buttonCommand)
mainClickButton.pack()

master.title("Cookie Clicker")
photo = PhotoImage(file=r"C:\Users\---\Desktop\Cookie.gif")
label = Label(image=photo)
label.image = photo
label.pack()
mainloop()

回答1:


I found this post :

Update Tkinter Label from variable

A bit modified this means :

from tkinter import *

master = Tk()

def uiPrint():
    print("")
    print(clickcount)
    blankLine()

clickcount=0
click=StringVar() #Updates label if changed
click.set("0");
mult = 1
dcp1 = 0

def blankLine():
    for i in range(20):
        print("") 

def buttonCommand():
    global clickcount
    global click
    global mult
    clickcount += 1*(mult)
    click.set(str(clickcount)); #Update score
    uiPrint()

mainClickButton = Button(master, text="Click me!", command = buttonCommand)
mainClickButton.pack()

master.title("Cookie Clicker")
photo = PhotoImage(file=r"C:\Users\---\Desktop\Cookie.gif")
label = Label(image=photo)
label.image = photo
label.pack()

l = Label(master, textvariable = click) #Score
l.pack()

mainloop();

I would additonaly suggest to make the cookie image as a button :

from tkinter import *

master = Tk()

def uiPrint():
    print("")
    print(clickcount)
    blankLine()

clickcount=0
click=StringVar() #Updates label if changed
click.set("0");
mult = 1
dcp1 = 0

def blankLine():
    for i in range(20):
        print("") 

def buttonCommand():
    global clickcount
    global click
    global mult
    clickcount += 1*(mult)
    click.set(str(clickcount)); #Update score
    uiPrint()

photo = PhotoImage(file=r"C:\Users\---\Desktop\Cookie.gif")
mainClickButton = Button(master, image=photo, command = buttonCommand)
mainClickButton.pack()

master.title("Cookie Clicker")

l = Label(master, textvariable = click) #Score
l.pack()

mainloop();

Both tested with python 2.7.11 and python 3.5.2, they work fine



来源:https://stackoverflow.com/questions/41642761/how-to-update-a-label-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!