python - 如何使用 Python 打印 Tkinter 标签中的变量?

标签 python tkinter

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

  1. 我应该将其设为全局变量并将其放入 textvariable=a 中吗?

  2. 我可以将其重定向到文本变量吗?

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

最佳答案

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

关于python - 如何使用 Python 打印 Tkinter 标签中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35829187/

相关文章:

python - 用python解压缩tar.Z文件?

python - 如何在 python 中将 float 转换为 timedelta 秒?

python - 按下按钮不返回 Tkinter 中的 Line2D 对象

python - 如何在 tkinter 中显示 matplotlib 图表

python - 你如何在 Tkinter 的事件循环中运行你自己的代码?

python - 类似于 append 行为的生成器表达式

python - 哪些单词在数据集中经常一起出现?

python - 多个标签掩码上的 Numpy,矢量化函数

Python tkinter : Countdown Timer not accurate

Python Tkinter,简单示例在 win 7 上失败