如何在python中更新标签?

时间:2017-01-13 20:14:44

标签: python tkinter label photo tk

我是python的新手,当我遇到问题时,我正在创建一个小游戏。我找了一个答案,发现了一个,但它没有用。

我尝试制作的游戏或多或少是Cookie Clicker的重新创建,我试图制作我在更新时得分的标签,而是创建一个新标签。

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 个答案:

答案 0 :(得分:0)

我找到了这篇文章:

Update Tkinter Label from variable

有点修改,这意味着:

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();

我会添加建议将cookie图像作为按钮:

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();

使用python 2.7.11和python 3.5.2进行测试,它们工作正常