【发布时间】:2015-05-26 17:23:53
【问题描述】:
我用 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() 检查用户的输入,然后在文本框中打印错误消息或将输入保存到变量以供进一步使用如果它被批准了。有什么好方法可以做到这一点吗?
非常感谢!
【问题讨论】:
-
你试过了吗?
-
我对 tkinter 很陌生,并且大部分时间都在浏览阅读指南和类似问题的示例,但我尝试了一些方法但收效甚微。我遇到的主要问题是文本框中的输入似乎无处可去。我尝试通过 Entry 小部件获取输入,然后通过 .get() 命令将输入定义到变量,但它没有返回任何内容!
-
如果你想让文本框的内容去某个地方,你必须告诉他们去哪里......除了一个在函数结束时被抛出的局部变量。跨度>
-
这就是我试图用文本框中的 .get() 命令完成的(不是在上面编写的代码中),这不可能吗?
标签: python input tkinter python-3.4