按下按钮更新 Tkinter 中的标签
Updating a label in Tkinter on a button press
我正在尝试制作一个按钮,单击该按钮会更新标签上的数字。我想要完成的是,当有人进球时,您可以点击目标!按钮,它将更新球队得分。
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()
希望有人能帮忙! python.
的新手
尝试使用将乐谱插入条目小部件的条目小部件,而不是使用标签。例如:
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
您的代码有两个问题。
第一个问题:
team1_attempt = Label(text = team1.score).pack()
这会将 team1_attempt
设置为 None
,因为 pack(0
returns None
。如果要保存对小部件的引用以便稍后与之交互,则必须分两步进行小部件创建和小部件布局。
第二题:
team1_attempt.set(text = self.score)
要更改小部件的属性,请使用 configure
方法。我不知道您阅读的是什么文档说要在标签小部件上调用 set
,但该文档是错误的。使用 configure
,像这样:
test1_attempt.configure(text=self.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()
希望有人能帮忙! python.
的新手尝试使用将乐谱插入条目小部件的条目小部件,而不是使用标签。例如:
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
您的代码有两个问题。
第一个问题:
team1_attempt = Label(text = team1.score).pack()
这会将 team1_attempt
设置为 None
,因为 pack(0
returns None
。如果要保存对小部件的引用以便稍后与之交互,则必须分两步进行小部件创建和小部件布局。
第二题:
team1_attempt.set(text = self.score)
要更改小部件的属性,请使用 configure
方法。我不知道您阅读的是什么文档说要在标签小部件上调用 set
,但该文档是错误的。使用 configure
,像这样:
test1_attempt.configure(text=self.score)