Python / Tkinter:从子窗口读取输入

时间:2013-04-19 06:35:34

标签: python user-interface tkinter

我正在准备一个使用Python和Tkinter的GUI应用程序(我是这种语言的新手)。

我有一个主窗口和一个配置子窗口,其中包含一些我打开的文本参数:

def config_open():
  global wdw, e
  wdw = Toplevel()
  wdw.geometry('+400+400')

  w = Label(wdw, text="Parameter 1", justify=RIGHT)
  w.grid(row=1, column=0)
  e = Entry(wdw)
  e.grid(row=1, column=1)
  e.focus_set()

然后我添加一个“OK”按钮,调用:

def config_save():
  global wdw, e
  user_input = e.get().strip()
  print user_input

它有效,但我宣称一切都是全球性的。有没有更好的方法来引用子窗口中的元素?

1 个答案:

答案 0 :(得分:1)

from Tkinter import *

def config_open():
    wdw = Toplevel()
    wdw.geometry('+400+400')
    # Makes window modal
    wdw.grab_set()

    # Variable to store entry value
    user_input = StringVar()
    Label(wdw, text="Parameter 1", justify=RIGHT).grid(row=1, column=0)
    e = Entry(wdw, textvariable=user_input)
    e.grid(row=1, column=1)
    e.focus_set()
    Button(wdw, text='Ok', command=wdw.destroy).grid(row=2, column=1)
    # Show the window and wait for it to close
    wdw.wait_window(wdw)
    # Window has been closed
    data = {'user_input': user_input.get().strip(),
            'another-option': 'value of another-option'}
    return data

class App:
    def __init__(self):
        self.root = Tk()
        self.root.geometry('+200+200')
        self.label_var = StringVar()
        self.user_input = None
        Button(self.root, text='Configure', command=self.get_options).place(relx=0.5, rely=0.5, anchor=CENTER)
        Label(self.root, textvariable=self.label_var).place(relx=0.5, rely=0.3, anchor=CENTER)
        self.root.mainloop()

    def get_options(self):
        options = config_open()
        self.user_input = options['user_input']
        self.label_var.set(self.user_input)

App()