如何在变量中保存DropDown的值

时间:2019-08-22 06:57:00

标签: python-3.x tkinter

在搜索并尝试了(不太好的)spyder调试器后,我仍然不知道为什么我的代码无法正常工作。 我想从下拉菜单中选择某项,然后根据选择的内容进行回报。

应该安静简单。窗口可以正常工作,我可以选择一个值,但是当我点击按钮时,错误:

NameError:名称'Selected_Report'未定义

但是我确实在select_Report函数(?)中定义了此变量,我认为这是一个愚蠢的错误,我只是看不到它。

谢谢!

from tkinter import *

REPORTS = [
"Alle Mitarbeiter",
"Alle Projekte",
"Alle Skills"
]

ReportSelection_Win = Tk()

variable = StringVar(ReportSelection_Win)
variable.set(REPORTS[0]) # default value

Lbl_Headline = Label(ReportSelection_Win, text = "Bitte wählen Sie einen Report")#Create Label
Lbl_Headline.grid(column=0, row=0, padx=10, pady=10) #Show Label

Drop_Reports = OptionMenu(ReportSelection_Win, variable, *REPORTS)
Drop_Reports.grid(column=0, row=1, padx=10, pady=0)

def Select_Report():
    Selected_Report = variable.get()
    ReportSelection_Win.destroy()

Btt_Confirm_2 = Button(ReportSelection_Win, text="Auswählen", command=Select_Report)
Btt_Confirm_2.grid(column=0, row=2, padx=10, pady=10)



ReportSelection_Win.mainloop()


#----------------------------Selected Report-----------------------------------

if Selected_Report == "Alle Mitarbeiter":
  print("Alle Mitarbeiter")

elif Selected_Report == "Alle Projekte":
  print("Alle Projekte")

elif Selected_Report == "Alle Skills":
  print("Alle Skills")

1 个答案:

答案 0 :(得分:1)

您需要告诉python您正在使用全局变量。你这样做 global [variable name]


from tkinter import *

REPORTS = [
"Alle Mitarbeiter",
"Alle Projekte",
"Alle Skills"
]


ReportSelection_Win = Tk()

variable = StringVar(ReportSelection_Win)
variable.set(REPORTS[0]) # default value

Lbl_Headline = Label(ReportSelection_Win, text = "Bitte wählen Sie einen Report")#Create Label
Lbl_Headline.grid(column=0, row=0, padx=10, pady=10) #Show Label

Drop_Reports = OptionMenu(ReportSelection_Win, variable, *REPORTS)
Drop_Reports.grid(column=0, row=1, padx=10, pady=0)

def Select_Report():
    global Selected_Report
    Selected_Report = variable.get()
    ReportSelection_Win.destroy()

Btt_Confirm_2 = Button(ReportSelection_Win, text="Auswählen", command=Select_Report)
Btt_Confirm_2.grid(column=0, row=2, padx=10, pady=10)



ReportSelection_Win.mainloop()


#----------------------------Selected Report-----------------------------------

print(Selected_Report)