如何在python中使用Tkinter输入到变量中

时间:2017-05-12 13:55:01

标签: python python-2.7 tkinter

我想知道如何从Tkinter获取输入并将其放入变量,如电话号码或一段文字。

3 个答案:

答案 0 :(得分:2)

from tkinter import *


def show_data():
    print( 'My First and Last Name are %s %s' % (fname.get(), lname.get()) )


win = Tk()
Label( win, text='First Name' ).grid( row=0 )
Label( win, text='Last Name' ).grid( row=1 )

fname = Entry( win )
lname = Entry( win )

fname.grid( row=0, column=1 )
lname.grid( row=1, column=1 )

Button( win, text='Exit', command=win.quit ).grid( row=3, column=0, sticky=W, pady=4 )
Button( win, text='Show', command=show_data ).grid( row=3, column=1, sticky=W, pady=4 )

mainloop()

答案 1 :(得分:0)

也许这可以帮到你:

from tkinter import *


def get_variable_value():
    valueresult.set( strlname.get() + ' ' + strfname.get() ) #assign val variable to other
    print(valueresult.get()) #if you want see the result in the console


root = Tk()

strfname = StringVar()
strlname = StringVar()
valueresult = StringVar()

labelf = Label(root, text = 'First Name').pack()
fname = Entry(root, justify='left', textvariable = strfname).pack() #strlname get input 

labell = Label(root, text = 'Last Name').pack()
lname = Entry(root, justify='left', textvariable = strlname).pack() #strfname get input 

button = Button(root, text='Show', command=get_variable_value).pack()
res = Entry(root, justify='left', textvariable = valueresult).pack() #only to show result


root.mainloop()

答案 2 :(得分:0)

下面是一个最小的GUI,它将条目中的内容写入变量,即按钮的文本:

import tkinter as tk

def replace_btn_text():
    b['text'] = e.get()

root = tk.Tk()

e = tk.Entry(root)
b = tk.Button(root, text="Replace me!", command=replace_btn_text)

e.pack()
b.pack()
root.mainloop()

相同的示例,但具有OOP结构:

import tkinter as tk


class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self._create_widgets()
        self._display_widgets()

    def replace_btn_text(self):
        """ Replaces button's text with what's written in the entry.
        """
                                        # self._e.get() returns what's written in the
        self._b['text'] = self._e.get() # entry as a string, can be assigned to a var.

    def _create_widgets(self):
        self._e = tk.Entry(self)
        self._b = tk.Button(self, text="Replace me!", command=self.replace_btn_text)

    def _display_widgets(self):
        self._e.pack()
        self._b.pack()


if __name__ == '__main__':
    root = App()
    root.mainloop()