【问题标题】:Save user input from tkinter to a variable and check its content将用户输入从 tkinter 保存到变量并检查其内容
【发布时间】:2015-05-26 17:23:53
【问题描述】:

我用 Python 编写了一个模拟纸牌游戏的脚本,用户可以在其中决定要玩多少张纸牌和多少堆纸牌。此输入由以下代码控制,其中boundary_1boundary_2 给出整数区间的上限和下限,消息是用户输入:

def input_check(boundary_1, message, boundary_2): 
    run = True
    while run:
        try:
            user_input =int(input(message))   
            if boundary_1 <= user_input <= boundary_2:

                run = False
                return user_input
            else:
                print ("Incorrect Value, try again!")
                run = True
        except ValueError:
            print ("Incorrect Value, try again!")

我现在想尝试使用 tkinter 从这个纸牌游戏中制作一个 GUI,因此我想知道是否有任何方法可以将用户的输入保存到可以发送到上面的 input_check() 函数的变量中?我已经阅读了一些关于 tkinter 的教程,发现了以下代码:

def printtext():
    global e
    string = e.get() 
    text.insert(INSERT, string)   

from tkinter import *
root = Tk()
root.title('Name')
text = Text(root)
e = Entry(root) 
e.pack()
e.focus_set()
b = Button(root,text='okay',command=printtext)
text.pack()
b.pack(side='bottom')
root.mainloop()

以下代码只是在文本框中打印用户的输入,我需要的是由我的input_check() 检查用户的输入,然后在文本框中打印错误消息或将输入保存到变量以供进一步使用如果它被批准了。有什么好方法可以做到这一点吗?

非常感谢!

【问题讨论】:

  • 你试过了吗?
  • 我对 tkinter 很陌生,并且大部分时间都在浏览阅读指南和类似问题的示例,但我尝试了一些方法但收效甚微。我遇到的主要问题是文本框中的输入似乎无处可去。我尝试通过 Entry 小部件获取输入,然后通过 .get() 命令将输入​​定义到变量,但它没有返回任何内容!
  • 如果你想让文本框的内容去某个地方,你必须告诉他们去哪里......除了一个在函数结束时被抛出的局部变量。跨度>
  • 这就是我试图用文本框中的 .get() 命令完成的(不是在上面编写的代码中),这不可能吗?

标签: python input tkinter python-3.4


【解决方案1】:

最简单的解决方案是使string全局:

def printtext():
    global e
    global string
    string = e.get() 
    text.insert(INSERT, string)   

当您这样做时,您的代码的其他部分现在可以访问string 中的值。

这不是最好的解决方案,因为过度使用全局变量会使程序难以理解。最好的解决方案是采用面向对象的方法,其中您有一个“应用程序”对象,该对象的属性之一就是“self.current_string”。

有关我建议您如何构建程序的示例,请参阅https://stackoverflow.com/a/17470842/7432

【讨论】:

  • 非常感谢您的快速回答!我想尽可能避免使用全局变量,所以我会尝试建议的面向对象的方法。我发现您对另一个示例的回答也非常有帮助,当我开始搜索有关使用类的文本输入的帖子时,我发现 stackoverflow.com/questions/15522336/text-input-in-tkinter 如果其他人试图解决同样的问题,这也是一个很好的例子!
猜你喜欢
  • 2016-12-31
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 2019-06-11
  • 1970-01-01
  • 1970-01-01
  • 2013-05-27
  • 1970-01-01
相关资源
最近更新 更多