Python 在 Tkinter 中接受用户的输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15495559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:15:47  来源:igfitidea点击:

Taking input from the user in Tkinter

pythontkinter

提问by IcyFlame

Goal

目标

  1. give the user a text field.
  2. Print the text that he entered in the field once he presses a button below it into the shell.
  1. 给用户一个文本字段。
  2. 一旦他将其下方的按钮按下到外壳中,就打印他在该字段中输入的文本。

How is this possible using Tkinter?

这怎么可能使用 Tkinter?

SpecsPython 2.7 on Linux Mint 14

Linux Mint 14 上的 Python 2.7规范

采纳答案by IcyFlame

We will take the text from the user using the Entrywidget. And then we will define a function that will extract the text from this widget and print it out in the shell.

我们将使用Entry小部件从用户那里获取文本。然后我们将定义一个函数,该函数将从这个小部件中提取文本并在 shell 中打印出来。

def printtext():
    global e
    string = e.get() 
    print string   

from Tkinter import *
root = Tk()

root.title('Name')

e = Entry(root)
e.pack()
e.focus_set()

b = Button(root,text='okay',command=printtext)
b.pack(side='bottom')
root.mainloop()

The window instance is first created. And then an Entrywidget is packed. After that another button widget is also packed. The focus_setmethod makes sure that the keyboard focus is on the text field when this is run. When the button is pressed it will go to the function which will extract the text from the Entrywidget using the getmethod.

首先创建窗口实例。然后一个Entry小部件被打包。之后,另一个按钮小部件也被打包。该focus_set方法确保在运行时键盘焦点位于文本字段上。当按下按钮时,它将转到Entry使用该get方法从小部件中提取文本的函数。

You can find more about the Entrywidget and its methods here:

您可以Entry在此处找到有关小部件及其方法的更多信息:

Entry Widget

条目小工具