[英]Updating a label in Tkinter on a button press
I am trying to make a button that when clicked updates the number on a label. 我试图做一个按钮,单击该按钮可以更新标签上的数字。 What I am trying to accomplish is that when someone scores a goal, you can click the Goal!
我要实现的目标是,当有人进球时,您可以点击目标! button and it will update the teams score.
按钮,它将更新团队得分。
import sys
from tkinter import *
root = Tk()
class team1:
score = 0
def goal(self):
self.score += 1
team1_attempt.set(text = self.score)
team1 = team1()
team1_attempt = Label(text = team1.score).pack()
team1_button = Button(text="Goal!", command = team1.goal).pack()
Hope someone can help! 希望有人能帮忙! New to python.
python新手。
You have two problems with your code. 您的代码有两个问题。
First problem: 第一个问题:
team1_attempt = Label(text = team1.score).pack()
This sets team1_attempt
to None
, because pack(0
returns None
. If you want to save a reference to a widget so you can interact with it later you must do widget creation and widget layout in two steps. 这
team1_attempt
设置为None
,因为pack(0
返回None
。如果要保存对小部件的引用,以便以后与之交互,则必须分两个步骤进行小部件创建和小部件布局。
Second problem: 第二个问题:
team1_attempt.set(text = self.score)
To change an attribute of a widget, use the configure
method. 要更改窗口小部件的属性,请使用
configure
方法。 I don't know what documentation you read that says to call set
on a label widget, but that documentation is wrong. 我不知道您阅读的文档中有什么说过调用标签小部件上的
set
,但是该文档是错误的。 Use configure
, like so: 使用
configure
,如下所示:
test1_attempt.configure(text=self.score)
Instead of using a label, try using an Entry widget that inserts the score into the Entry widget. 代替使用标签,尝试使用将得分插入“入口”窗口小部件的“入口”窗口小部件。 For example:
例如:
class test:
def __init__(self, master):
self.goalButton = Button(master,
text = "goal!",
command = self.goalUpdate)
self.goalButton.pack()
self.goalDisplay = Entry(master,
width = 2)
self.goalDisplay.pack()
self.score = 0
def goalUpdate(self):
self.goalDisplay.delete(1.0, END) # Deletes whatever is in the score display
score = str(self.score)
self.goalDisplay.insert(0, score) # Inserts the value of the score variable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.