可以在Tkinter中显示python输入语句吗?

可以在Tkinter中显示python输入语句吗?,python,tkinter,Python,Tkinter,我有python代码,它接受用户输入,因此我使用了很多输入语句。现在我正在使用Tkinter创建GUI,并希望在Tkinter中显示这些输入语句。有办法吗 例如 var=float(input("enter a number")) 现在我想显示输入语句“在Tkinter中输入一个数字”。有可能吗?如果是,如何操作?您可以使用tkinter的askstring命令,而不是使用输入功能。这将弹出一个小对话框,其中包含询问的问题,并将用户的输入返回到脚本中 import tkinter as tk

我有python代码,它接受用户输入,因此我使用了很多输入语句。现在我正在使用Tkinter创建GUI,并希望在Tkinter中显示这些输入语句。有办法吗

例如

var=float(input("enter a number"))

现在我想显示输入语句“在Tkinter中输入一个数字”。有可能吗?如果是,如何操作?

您可以使用tkinter的
askstring
命令,而不是使用
输入功能。这将弹出一个小对话框,其中包含询问的问题,并将用户的输入返回到脚本中

import tkinter as tk
import tkinter.simpledialog as sd

def getUserInput():
    userInput = sd.askstring('User Input','Enter your name')
    print(f'You said {userInput}')

root = tk.Tk()
btn = tk.Button(root,text="Get Input", command=getUserInput)
btn.grid()
root.mainloop()
如果您希望询问数值,tkinter还具有
askfloat
askinteger
功能。这些允许您指定最小值和最大值

import tkinter as tk
import tkinter.simpledialog as sd

def getUserInput():
    userInput = sd.askstring('User Input','Enter your name')
    print(f'You said {userInput}')

def getUserFloatInput():
    options = {'minvalue':3.0,'maxvalue':4.0}
    userInput = sd.askfloat('User Input','Enter an approximation of Pi',**options)
    print(f'You said pi is {userInput}')

def getUserIntegerInput():
    options = {'minvalue':4,'maxvalue':120}
    userInput = sd.askinteger('User Input','How old are you?',**options)
    print(f'You said you are {userInput}')

root = tk.Tk()
btn1 = tk.Button(root,text="Get String Input", command=getUserInput)
btn1.grid()
btn2 = tk.Button(root,text="Get Float Input", command=getUserFloatInput)
btn2.grid()
btn3 = tk.Button(root,text="Get Integer Input", command=getUserIntegerInput)
btn3.grid()
root.mainloop()

input
从控制台读取其值,但tkinter提供gui。这使得控制台对于用户输入是多余的。您应该使用TextBox小部件或类似的小部件。除非您希望从终端运行并使用这些语句来构建GUI本身,否则它可能是有意义的。无论如何,这太宽泛了-签出
tkinter
Label
小部件,它有一个
var
参数。你是说tkinter应用程序的类似控制台的行为吗?如果是这样,您可以将输入/输出重定向到
stdin
/
stdout
streams.CommonSense-是的,我指的是类似控制台的行为。我知道如何将打印语句重定向/发送到GUI文本框:sys.stdout=PrintOutput()。但如何将输入语句从代码重定向到GUI?