将来自 tkinter 的用户输入保存到变量并检查其内容
Save user input from tkinter to a variable and check its content
我在 Python 中编写了一个模拟纸牌游戏的脚本,用户可以在其中决定要玩多少张纸牌和多少堆纸牌。此输入由以下代码控制,其中 boundary_1
和 boundary_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()
检查用户的输入,然后在文本框中打印错误消息或将输入保存到变量中如果获得批准,可以进一步使用。有什么好的方法可以做到这一点吗?
非常感谢!
最简单的解决方案是使 string
全局化:
def printtext():
global e
global string
string = e.get()
text.insert(INSERT, string)
当您这样做时,代码的其他部分现在可以访问 string
中的值。
这不是最好的解决方案,因为过度使用全局变量会使程序难以理解。最好的解决方案是采用面向对象的方法,您有一个 "application" 对象,并且该对象的属性之一类似于 "self.current_string".
有关我建议您如何构建程序的示例,请参阅
我在 Python 中编写了一个模拟纸牌游戏的脚本,用户可以在其中决定要玩多少张纸牌和多少堆纸牌。此输入由以下代码控制,其中 boundary_1
和 boundary_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()
检查用户的输入,然后在文本框中打印错误消息或将输入保存到变量中如果获得批准,可以进一步使用。有什么好的方法可以做到这一点吗?
非常感谢!
最简单的解决方案是使 string
全局化:
def printtext():
global e
global string
string = e.get()
text.insert(INSERT, string)
当您这样做时,代码的其他部分现在可以访问 string
中的值。
这不是最好的解决方案,因为过度使用全局变量会使程序难以理解。最好的解决方案是采用面向对象的方法,您有一个 "application" 对象,并且该对象的属性之一类似于 "self.current_string".
有关我建议您如何构建程序的示例,请参阅