是否可以在 Tkinter 下拉菜单中输入用户文本?如果是这样,如何?

Is it possible take user text input in a Tkinter dropdown menu? If so, how?

这是我试过的:

win = Tk()
menubar = Menu(win)
dropDown = Menu(menubar)
dropDown.add_command(label = "Do something", command = ...)

entry = Entry()
dropDown.add(entry)

menubar.add_cascade(label = "Drop Down", menu = dropDown)
win.config(menu = menubar)
win.update()

我查看了文档,似乎没有办法用像 dropDown.add_entry(...) 这样的单行来完成,但我认为可能有一种解决方法,比如使用几何管理器之一来以某种方式将条目放入菜单中。

我正在使用 Python 3.6(但我没有标记它,因为我会从 Python 标签中得到一千个模组,他们没有兴趣回答我的问题投票关闭没有理由)

不,使用标准菜单无法获得接受用户输入的菜单。这根本不是菜单设计的工作方式。

如果需要用户输入字符串,则需要使用对话框。

这是一个简单的程序,您可以在其中单击菜单按钮来提示用户输入。然后用那个输入做点什么。在这种情况下打印到控制台。

我们需要编写一个使用 askstring() 来自 simpledialog 的函数,您可以从 Tkinter 导入它。然后获取用户键入的字符串的结果并对其进行处理。

import tkinter as tk
from tkinter import simpledialog


win = tk.Tk()
win.geometry("100x50")

def take_user_input_for_something():
    user_input = simpledialog.askstring("Pop up for user input!", "What do you want to ask the user to input here?")
    if user_input != "":
        print(user_input)

menubar = tk.Menu(win)
dropDown = tk.Menu(menubar, tearoff = 0)
dropDown.add_command(label = "Do something", command = take_user_input_for_something)

# this entry field is not really needed her.
# however I noticed you did not define this widget correctly
# so I put this in to give you an example.
my_entry = tk.Entry(win)
my_entry.pack()

menubar.add_cascade(label = "Drop Down", menu = dropDown)
win.config(menu = menubar)

win.mainloop()