在tkinter python中单击按钮即可更新标签文本

问题描述 投票:-1回答:1

我试图获得一个标签,以在单击按钮时显示一个随机数。我已经在函数中尝试过get(),set()和config(),就像在stackoverflow上的类似情况一样,但无济于事。我哪里出错了?

import tkinter as tk
import random

HEIGHT=200            #Window height
WIDTH=300             #Window width
TITLE="Random number" #Window title

LWIDTH=40             #Label width
LHEIGHT=50            #Label height
LFONTSIZE=44          #Label font size

def buttonpress():
    LTEXT.set(random.randint(0, 100)) #The intention is for a new value to be calculated
    l.text=LTEXT                      #The intention is for the label text to be updated. Have tried set(), get(), config()

BUTTONWIDTH=17    #button width
BUTTONHEIGHT=2    #button height, but in rows instead of pixels (!!!)

root=tk.Tk()
root.title(TITLE)

LTEXT=tk.IntVar(root)               #defining the intvar
LTEXT.set(random.randint(0, 100))   #setting the initial value

f = tk.Frame(root,width=WIDTH,height=HEIGHT)
f.pack()

l=tk.Label(width=LWIDTH, height=LHEIGHT, text=LTEXT.get(),font=(None,LFONTSIZE))
l.place(relx=0.5, rely=0.3, anchor="center")

b=tk.Button(root,width=BUTTONWIDTH, height= BUTTONHEIGHT, text = "New number",command=buttonpress())
b.place(relx=0.5, rely=0.7, anchor="center")

root.mainloop()
python button tkinter click label
1个回答
1
投票

要从标签中获取文本:print(mylabel["text"])

因此进行修改:mylabel["text"] = myrandomnumber

它适用于所有参数,适用于所有参数,按钮,标签,画布等...

示例:

from tkinter import *
root = Tk()
label = Label(text="hello")
def change():
    label["text"] = "world"
button = Button(text="Change", command=change)
label.pack()
button.pack()
© www.soinside.com 2019 - 2024. All rights reserved.