1

所以我正在尝试制作某种基本的自动点击器,其排名会在一定数量的点击后更新,但是每当我更新排名时,应该显示的标签不会改变,我不知道如何进行标签更新

from tkinter import *

count = 0
rank = "click the button to rank up!"

window = Tk()

if count == 1:
    rank = "wow first click!"

def click():
    global count
    count += 1
    counter = Label(window, text=count).grid(row = 0, column = 1)

clicker = Button(window, text="The Button", padx = 50, pady = 50, command = click).grid(row = 0, column = 0)

rankDisplay = Label(window, text = rank, padx = 100, pady = 25).grid(row = 1, column = 0)
  
window.mainloop()

第一次点击后,排名仍然显示为“点击按钮排名上升”而不是“哇第一次点击”,这几乎是问题

4

3 回答 3

1

这是代码:

from tkinter import *

count = 0

window = Tk()
def changed(text):
    rankDisplay.config(text=text)
    rankDisplay.grid(row = 1, column = 0)
def click():
    global count
    count += 1
    counter = Label(window, text=count).grid(row = 0, column = 1)
    if count == 1:
        changed("wow first click!")
    return count
clicker = Button(window, text="The Button", padx = 50, pady = 50, command = click).grid(row = 0, column = 0)
rankDisplay = Label(window, text = "", padx = 100, pady = 25)
changed("click the button to rank up!")
  
window.mainloop()

当您单击按钮时,标签文本将“单击按钮以排名”更新为“哇第一次单击”。因为标签的文本是 StringVar(),如果我设置了 stringvar,那么标签的文本将更新为 stringvar

于 2021-08-24T05:18:11.837 回答
0

我已经知道这个问题了。要解决这个问题,您必须为您的标签创建一个全局变量:

global l1
l1 = Label(...)

然后,要修改文本,你必须在你的函数中做:

l1.config(text=str(count))
于 2021-08-23T21:19:56.543 回答
0

请参阅此处,您应该使用update名为的标签的方法rankDisplay

这是代码:

from tkinter import *

count = 0



window = Tk()

rank = StringVar()
rank.set("Click the button to rank up")


def click():
    global count
    count += 1
    counter = Label(window, text=count).grid(row=0, column=1)
    if count == 1:
        rank.set("wow first click!")
        rankDisplay.update()


clicker = Button(window, text="The Button", padx=50, pady=50, command=click).grid(row=0, column=0)

rankDisplay = Label(window, textvariable=rank, padx=100, pady=25)
rankDisplay.grid(row=1, column=0)

window.mainloop()

修改你的代码:你应该知道StringVar在 tkinter 中使用该update方法的概念。链接了解它https://www.pythontutorial.net/tkinter/tkinter-stringvar/#:~:text=The%20Tkinter%20StringVar %20helps%20you,Label%20or%20Entry%20more%20effectively.&text=%20StringVar%20constructor%20accepts%20three,defaults%20to%20the%20root%20window

并且在rankDisplay标签中你必须使用textvariable属性而不是text

只有这些是变化...

于 2021-08-24T05:44:04.703 回答