如何在python的下拉菜单中添加文本框供用户输入?

时间:2019-01-23 00:25:09

标签: python user-interface tkinter

我正在创建一个酒店入住系统,希望用户能够选择他们想做的事情,然后将弹出一组文本框供用户输入。

我已经创建了下拉菜单

master = Tk()

master.title("*** HOTEL BOOKING SYSTEM ***")

master.geometry('350x200')

variable = StringVar(master)

variable.set("Select what you'd like to do") # default value

lbl = OptionMenu(master, variable, "1. Enter Guest Details.", "2. Enter Room Details.", "3. Allocate Key.", "4. Simulate Guest first entry.", "5. Room key is lost/not returned")

lbl.pack()


master.mainloop()

例如,使用“输入来宾详细信息”,我希望显示一个文本框,询问您的来宾姓名,出生日期等。我希望这是可能的,并且希望得到任何帮助

1 个答案:

答案 0 :(得分:-1)

您可以根据用户选择,以编程方式创建必要的窗口小部件,例如EntryButton。但是,在主窗口中很难做到这一点。同样,每个选择都需要各种数量的小部件等。

我建议您使用TopLevel窗口。因此,您可以检查用户选择,然后在此基础上pop-up可以打开一个窗口。因此,每个pop-up窗口将特定于用户选择。  您可以在此处找到示例:

import tkinter as tk

class MainWindow:
    def __init__(self, master):
        self.master = master
        self.variable = tk.StringVar(root)
        self.variable.set('')
        self.lbl = tk.OptionMenu(root, self.variable, "1. Enter Guest Details.", "2. Enter Room Details.", "3. Allocate Key.",
                            "4. Simulate Guest first entry.", "5. Room key is lost/not returned")
        self.lbl.pack()
        self.button = tk.Button(self.master, text='Pop-Up', command=lambda:self.check_value())
        self.button.pack()

    def check_value(self):
        if self.variable.get() == '1. Enter Guest Details.':
           self.pop_up()

    def pop_up(self):
        # Create top level window for user to input
        save_window_toplevel = tk.Toplevel(self.master)
        save_window_toplevel.geometry("400x200+100+100")
        # Initiate a save window
        save_window = SaveWindow(master=save_window_toplevel)
        # wait user to input valid filename
        save_window_toplevel.wait_window()

class SaveWindow:
    def __init__(self, master):
        self.master = master
        self.top_frame = tk.Frame(self.master, relief="solid")
        self.top_frame.pack(side="top", fill="none", expand=True)
        self.label_1 = tk.Label(self.top_frame, text="Guest Name: ")
        self.label_1.grid(row=0, column=0, sticky="w", padx=5, pady=5)
        self.username_entry = tk.Entry(self.top_frame, width=20)
        self.username_entry .grid(row=0, column=1, padx=5, pady=5)
        self.save_button = tk.Button(self.top_frame, text="Save", command=lambda: self.read_username())
        self.save_button.grid(row=1, column=0, columnspan=2, pady=20)

    def read_username(self):
        print('Guest name is {}'.format(self.username_entry.get()))
        self.master.destroy()

if __name__ == '__main__':
    root = tk.Tk()
    app = MainWindow(master=root)
    root.mainloop()

我希望它能给您一个想法。