我无法生成一个随机数并打印出来

时间:2018-06-05 16:11:28

标签: python random tkinter

我无法生成数字,因为我收到错误NameError:name'z'未定义。

import tkinter as tk
from random import randint

def randomize():
    z.set ( randint(x.get(),y.get()))

root = tk.Tk()

x = tk.IntVar()
y = tk.IntVar()

text= tk.Label(root, text = "press the button for random number")
enterX = tk.Entry(root)
enterY = tk.Entry(root)
button = tk.Button(root, text = "Press here", command=randomize)
result = tk.Label(root,text="Number is:")
number = tk.Label(root, textvariable=z)

text.pack()
enterX.pack()
enterY.pack()
button.pack()
result.pack()
number.pack()

root.mainloop()

我需要帮助来解决错误

1 个答案:

答案 0 :(得分:1)

这里有2个问题。

一。您在全局命名空间中缺少z = tk.Intvar()

两个。您需要为IntVar()中的每个输入字段分配一个

请记住,您没有验证输入字段,因此如果有人输入除整数之外的任何内容,您将会遇到错误。

看看这段代码。

import tkinter as tk
from random import randint

def randomize():
    z.set(randint(x.get(),y.get()))
    print(z.get()) # added print statement to verify results.

root = tk.Tk()

x = tk.IntVar()
y = tk.IntVar()
z = tk.IntVar() # added IntVar()

text= tk.Label(root, text = "press the button for random number")
enterX = tk.Entry(root, textvariable=x) # added textvariable
enterY = tk.Entry(root, textvariable=y) # added textvariable
button = tk.Button(root, text = "Press here", command=randomize)
result = tk.Label(root,text="Number is:")
number = tk.Label(root, textvariable=z)

text.pack()
enterX.pack()
enterY.pack()
button.pack()
result.pack()
number.pack()

root.mainloop()