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

最新更新