如何使用Python在Tkinter标签中打印变量?

2024-06-10 21:09:43 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在GUI标签中打印变量?在

  1. 我应该把它变成一个全局变量并放在textvariable=a中吗?

  2. 我能把它重定向到textvariable吗?

  3. 还有别的办法吗?

#Simple program to randomly choose a name from a list

from Tkinter import * #imports Tkinter module
import random  #imports random module for choice function
import time #imports time module

l=["Thomas", "Philip", "John", "Adam", "Kate", "Sophie", "Anna"]       #creates a list with 7 items
def pri():  #function that asigns randomly item from l list to     variable a and prints it in CLI
    a = random.choice(l) #HOW CAN I PRINT a variable IN label     textvarible????
    print a     #prints in CLI
    time.sleep(0.5)


root = Tk()                 #this
frame = Frame(root)         #creates
frame.pack()                #GUI frame
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )

#GUI button
redbutton = Button(frame, text="Choose name", fg="red", command = pri)
redbutton.pack( side = LEFT)

#GUI label
var = StringVar()
label = Label(bottomframe, textvariable= var, relief=RAISED )
label.pack( side = BOTTOM)

root.mainloop() 

Tags: fromimporttimeguirandomrootframeside
1条回答
网友
1楼 · 发布于 2024-06-10 21:09:43
from Tkinter import *
import time
import random

l=["Thomas", "Philip", "John", "Adam", "Kate", "Sophie", "Anna"]       #creates a list with 7 items
def pri():  #function that asigns randomly item from l list to     variable a and prints it in CLI
    a = random.choice(l) #HOW CAN I PRINT a variable IN label     textvarible????
    print a     #prints in CLI
    time.sleep(0.5)
    return a


root = Tk()

var = IntVar() # instantiate the IntVar variable class
var.set("Philip")     # set it to 0 as the initial value

# the button command is a lambda expression that calls the set method on the var,
# with the var value (var.get) increased by 1 as the argument
Button(root, text="Choose name", command=lambda: var.set(pri())).pack()

# the label's textvariable is set to the variable class instance
Label(root, textvariable=var).pack()

mainloop()

相关问题 更多 >