【问题标题】:How can I print text based on the value in a dropdown menu如何根据下拉菜单中的值打印文本
【发布时间】:2020-05-13 09:24:55
【问题描述】:

我尝试制作一个 tkinter 脚本,该脚本将根据下拉菜单中选择的日期打印一组作业,但它不起作用,我找不到任何解决方案。感谢你的帮助! 我的代码:

from tkinter import *

root = Tk()
root.geometry("500x500")
Label(root, text="Day").pack()
OPTIONS = [
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    "Sunday"

]
variable = StringVar()
variable.set("Day")
w = OptionMenu(root, variable, *OPTIONS).pack()


def day():
    if variable == "Monday":
        print("Hello")



Button(root, text="Enter", command=day).pack()

root.mainloop()

【问题讨论】:

标签: python python-3.x tkinter


【解决方案1】:

您的代码存在三个问题。

variable = StringVar()
w = OptionMenu(root, variable, *OPTIONS).pack()
# Try to set the value here will make more sence if you reed it back
# after some weeks. Plus try to use week days. "Day" is not a week day
# and in the future will prevent an error... I know better
variable.set(OPTIONS[0])
def day():
    # You forget .get() and alos I suggest to use .lower()
    if variable.get().lower() == "monday":
        print("Hello")
# Lambda will prevet that code to bexecuted before button is pressed
Button(root, text="Enter", command=lambda:day()).pack()
```

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    相关资源
    最近更新 更多