将Tkinter条目的值赋给Python变量

2024-10-01 09:40:24 发布

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

我目前正在学习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检查随机生成的数字。我真的不知道该从这里开始,或者如何持续检查,如果猜测不正确,如何重新分配变量。在


Tags: importtkinterrandomlabelpacktkint对话框
1条回答
网友
1楼 · 发布于 2024-10-01 09:40:24

手动

根据The Tkinter Entry Widget

首先,您可以使用

entry.get()

其次,可以将其绑定到tkinter.Variable(它创建并包装一个具有自动生成名称的Tcl全局变量)。通常,它的子类StringVar用于在获取/设置时将值转换为str。在

^{pr2}$

正如你所看到的,差别不大,只是增加了一个间接的层次。这两种方法都会得到一个str,所以你需要用int()来解析它。但是您可以使用一个IntVar,而不是Variable(或StringVar),它将在.get()上为您解析它(如果它不是有效的整数,则会引发ValueError)。在

自动

要在Entry的值更改时自动更新Python变量,请使用Variable.trace_add

def callback(tcl_name,index,op):
    global myvar
    # See https://tcl.tk/man/tcl8.6/TclCmd/trace.htm#M14 about the arguments.
    # A callback is only passed the name of the underlying Tcl variable
    # so have to construct a new Variable of the same class on the fly 
    # that wraps it to get the value and convert it to the appropriate type.
    # Yes, it's this hacky.
    try: myvar = StringVar(tcl_name).get()
    except ValueError: myvar = None

v.trace_add("write",callback)

对于callback来说,一个不那么老套的解决方案是使回调成为Variable的实例方法。这样,它将通过self获得对它的引用,而不必构造一个新的类实例。该值也可以作为实例属性:

def callback(self,*args):
    try: self.value=self.get()
    except ValueError: self.value=None

v.callback=callback
v.trace_add("write",v.callback)

请注意,这将在每次更改时调用,也就是说,即使您键入值,也可能会导致GUI反应的明显延迟。因此,除非您真的需要不断监视该值,否则只需在适当的时候读取一次就足够了。在

相关问题 更多 >