简体   繁体   中英

Updating a label text with the click of a button in tkinter python

I am trying to get a label to display a random number when a button is clicked. I have tried get(), set() and config() in the function, as per similar cases on stackoverflow but to no avail. Where do I go wrong?

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

To get the text form your label: print(mylabel["text"])

So to modify it: mylabel["text"] = myrandomnumber

It works with every parameter, for everything, buttons, labels, canvas, etc...

Exemple:

from tkinter import *
root = Tk()
label = Label(text="hello")
def change():
    label["text"] = "world"
button = Button(text="Change", command=change)
label.pack()
button.pack()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM