我目前正在学习python,遇到了一个障碍。我从java开始,喜欢使用JOptionPane作为输入对话框,并使用这些对话框为变量赋值并从那里解析它们。在
在python中,我注意到人们将Tkinter用于大多数基本的gui设置,但是我找不到很多关于如何使用Tkinter创建的文本框为变量赋值的信息。我的代码如下:
import random
import tkinter as tk
def guess():
global entry
guess = entry.get()
guessN = int(guess)
root1 = tk.Tk()
label = tk.Label(root1, text='What number am I thinking of between 1 and 100?')
entry = tk.Entry(root1)
entry.focus_set()
b = tk.Button(root1,text='okay',command=guess)
b.pack(side='bottom')
label.pack(side = tk.TOP)
entry.pack()
root1.mainloop():
x = random.randint(1,101)
guess()
tries = 0
while guessN != x:
if (guessN < x):
guess = input("Too low! Try again.")
guessN = int(guess)
tries += 1
else:
guess = input("Too high! Try again.")
guessN = int(guess)
tries += 1
print('Congratulations you guessed the number', x, 'in', tries, 'tries!')
SystemExit
我想使用tkinter将输入分配给guess,然后使用guessN检查随机生成的数字。我真的不知道该从这里开始,或者如何持续检查,如果猜测不正确,如何重新分配变量。在
手动
根据The Tkinter Entry Widget:
首先,您可以使用
其次,可以将其绑定到
^{pr2}$tkinter.Variable
(它创建并包装一个具有自动生成名称的Tcl全局变量)。通常,它的子类StringVar
用于在获取/设置时将值转换为str
。在正如你所看到的,差别不大,只是增加了一个间接的层次。这两种方法都会得到一个
str
,所以你需要用int()
来解析它。但是您可以使用一个IntVar
,而不是Variable
(或StringVar
),它将在.get()
上为您解析它(如果它不是有效的整数,则会引发ValueError
)。在自动
要在
Entry
的值更改时自动更新Python变量,请使用Variable.trace_add
:对于
callback
来说,一个不那么老套的解决方案是使回调成为Variable
的实例方法。这样,它将通过self
获得对它的引用,而不必构造一个新的类实例。该值也可以作为实例属性:请注意,这将在每次更改时调用,也就是说,即使您键入值,也可能会导致GUI反应的明显延迟。因此,除非您真的需要不断监视该值,否则只需在适当的时候读取一次就足够了。在
相关问题 更多 >
编程相关推荐