首页 > 解决方案 > 是否可以在 Tkinter 中显示 python 输入语句?

问题描述

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

例如。

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

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

标签: pythontkinter

解决方案


input您可以使用 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 也有askfloataskinteger功能。这些允许您指定最小值和最大值。

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()

推荐阅读