Python Tkinter Def改变Var

时间:2016-02-22 10:27:45

标签: python variables tkinter

我还在学习Tkinter,我正在尝试制作一个简单的程序,按一下按钮就会生成三个随机的nums,但def不会改变var,它会将它打印到控制台但不会改变vars < / p>

from tkinter import *
import random

firstNum = 0
secondNum = 0
thirdNum = 0

def PickNewNums():
    firstNum = random.randint(1, 100)
    secondNum = random.randint(1, 100)
    thirdNum = random.randint(1, 100)
    print(firstNum)
    return firstNum, secondNum, thirdNum

root = Tk()


mainTitle = Label (root, text = "Amazing Title")
newNumbers = Button(root, text = "Get New Numbers", command=PickNewNums)

firstNumber = Label(root, text = firstNum)
secondNumber = Label(root, text = secondNum)
thirdNumber = Label(root, text = thirdNum)

mainTitle.pack()
firstNumber.pack()
secondNumber.pack()
thirdNumber.pack()
newNumbers.pack(side = BOTTOM)
root.geometry("600x300")
root.mainloop()

感谢大家的帮助!

1 个答案:

答案 0 :(得分:0)

我更喜欢在课堂上包装东西。

您可以将Tkinter变量与标签相关联。当变量的内容发生变化时,标签会自动更新:

v = StringVar()
Label(root, textvariable=v).pack()

更新do:

v.set("Hest!")