我最近在這里詢問并回答了這個問題以供參考: TKinter ComboBox 變數問題
我現在添加一個按鈕和功能來顯示選擇的選項。我相信這個問題與這是一本字典而不是一個串列有關。這是到目前為止我的課程的一個片段:
# ---------------- HP Pool Option --------------#
hp_pool_options = {"Low" : (
"5","10","15","20",
"25","30","35","40",
"45","50","55","60",
"65","70","75","80",
"85","90","95","100"),
"Medium" : (
"105","110","115","120",
"125","130","135","140",
"145","150","155","160",
"165","170","175","180",
"185","190","195","200",),
"High" : (
"205","210","215","220",
"225","230","235","240",
"245","250","255","260",
"265","270","275","280",
"285","290","295","300",),
"Extreme" : (
"325","350","375","400",
"425","450","475","500",
"525","550","575","600",
"625","650","675","700",
"725","750","775","800",)}
def on_pool_selected(hp_value):
hp_values = ('Random',)
if hp_value == 'Random':
for v in hp_pool_options.values():
hp_values = v
else:
hp_values = hp_pool_options[hp_value]
hp_value_combobox.configure(values=hp_values)
hp_value_combobox.set('Random')
#Label
hp_pool_label = customtkinter.CTkLabel(master=self.frame_left, text="HP Option")
hp_pool_label.grid(row=5,column=0)
hp_var1 = customtkinter.StringVar()
hp_pool_combobox = customtkinter.CTkComboBox(master=self.frame_left,
variable=hp_var1,
values=("Random",) tuple(hp_pool_options.keys()),
command=on_pool_selected)
hp_pool_combobox.grid(row=5, column=1)
hp_var2 = customtkinter.StringVar()
hp_value_combobox = customtkinter.CTkComboBox(master=self.frame_left, variable=hp_var2)
hp_value_combobox.grid(row=5, column=2)
hp_value_combobox.set("Random")
hp_pool_combobox.set("Random")
#TODO
#Add HP Value function
def add_hp_value():
hp_value_choice = StringVar()
hp_value_choice = hp_value_combobox.get()
random_hp_value = random.choice(hp_values)
if hp_value_choice == "Random":
display_hp_value['text'] = random_hp_value
else:
display_hp_value['text'] = hp_value_choice
#Display HP Value
display_hp_value = customtkinter.CTkLabel(master=self.frame_right, text='')
display_hp_value.grid(row=5,column=1)
#Create button to add HP Value
add_hp_value_btn = customtkinter.CTkButton(master=self.frame_left, text="Add HP Value", command=add_hp_value())
add_hp_value_btn.grid(row=5, column=3)
我看到的問題在于按鈕功能。random_hp_value 試圖從 hp_values 中提取但超出范圍。如何將這些 hp_values 回傳到串列變數中,然后放入我的按鈕函式中?
uj5u.com熱心網友回復:
您可以使用 的屬性values來hp_value_combobox獲取組合框的值。要排除該Random值,請使用hp_value_combox.values[1:].
def add_hp_value():
...
random_hp_value = random.choice(hp_value_combobox.values[1:])
...
也command=add_hp_value()將立即執行add_hp_value。改為使用command=add_hp_value。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/490462.html
上一篇:在tkinter中關閉多個頂層
