在 python tkinter 中更新标签变量

update label variable in python tkinter

from tkinter import *
import tkinter as tk
import random

f = 0

def test_print():
    f = random.randint(0,118)
    master.update_idletasks()

# creating Tk window
master = Tk()

master.minsize(600,400)
 
var = IntVar()
var.set(f)

# cretaing a Fra, e which can expand according
# to the size of the window
pane = Frame(master)
pane.pack(fill = BOTH, expand = True)
 
# button widgets which can also expand and fill
# in the parent widget entirely
# Button 1
b1 = Button(pane, text = "Click me !", 
            background = "red", fg = "white", command = test_print)
b1.pack(side = TOP, expand = True, fill = BOTH)
 
label = tk.Label(pane, textvariable = var)
label.pack(side = BOTTOM, expand = False)

# Execute Tkinter
master.mainloop()

这段代码运行良好,但是当我按下按钮时它没有给我一个随机数。我需要它给我一个随机输出,这样我就可以从列表中获取一个随机元素。有人知道这个问题的答案吗?

在这里。现在您可以看到标签发生了变化:

from tkinter import *
import tkinter as tk
import random


def test_print():
    f = random.randint(0, 118)
    label.configure(text=str(f))
    master.update_idletasks()


# creating Tk window
master = Tk()

master.minsize(600, 400)

# cretaing a Fra, e which can expand according
# to the size of the window
pane = Frame(master)
pane.pack(fill=BOTH, expand=True)

# button widgets which can also expand and fill
# in the parent widget entirely
# Button 1
b1 = Button(pane, text="Click me !",
            background="red", fg="white", command=test_print)
b1.pack(side=TOP, expand=True, fill=BOTH)

label = tk.Label(pane)
label.pack(side=BOTTOM, expand=False)

# Execute Tkinter
master.mainloop()

答案在这里

from tkinter import *
import tkinter as tk
import random

maxnumber = 118
f = random.randint(0,maxnumber)
def test_print():
   master.update_idletasks()
   label.configure(textvariable = var)

# creating Tk window
master = Tk()

master.minsize(600,400)

var = IntVar()
var.set(f)

# cretaing a Fra, e which can expand according
# to the size of the window
pane = Frame(master)
pane.pack(fill = BOTH, expand = True)

# button widgets which can also expand and fill
# in the parent widget entirely
# Button 1
b1 = Button(pane, text = "Click me !", 
        background = "red", fg = "white", command = test_print)
b1.pack(side = TOP, expand = True, fill = BOTH)

label = tk.Label(pane)
label.pack(side = BOTTOM, expand = False)

# Execute Tkinter
master.mainloop()