如何在Python中使用else语句?实现下拉框选中Volume时显示对应选项
实现下拉框联动显示功能
实现步骤
- 初始状态下隐藏
unitsecond及其标签lbl_from - 给
unitfirst绑定选中事件,触发判断逻辑 - 通过
if-else语句判断选中值,控制控件的显示/隐藏
修改后的完整代码
import tkinter as tk from tkinter import ttk main_frame = tk.Tk() main_frame.configure(bg='dark blue') main_frame.geometry('600x300') # 定义需要的变量 unitunit = tk.StringVar() unitfrom = tk.StringVar() #=== Label for 'Unit' & Combobox === lbl_unit = tk.Label(main_frame, text='Unit', font=('arial',16,'bold'), fg='white',bg='dark blue') lbl_unit.place(x=180,y=100) unitfirst = ttk.Combobox(main_frame,textvariable=unitunit, font=('arial',16),width=10,state='readonly') unitfirst['value'] = ('Select Unit','Volume','Length', 'Mass') unitfirst.current(0) unitfirst.place(x=280,y=100) #=== Label for 'From' & Combobox === lbl_from = tk.Label(main_frame, text='From', font=('arial',16,'bold'), fg='white',bg='dark blue') # 初始隐藏标签 lbl_from.place_forget() #=== combobox == unitsecond = ttk.Combobox(main_frame,textvariable=unitfrom, font=('arial',16),width=10,state='readonly') unitsecond['value'] = ('Select Unit','ml','l') unitsecond.current(0) # 初始隐藏下拉框 unitsecond.place_forget() # 事件处理函数 def on_unit_selected(event): selected_unit = event.widget.get() if selected_unit == 'Volume': # 显示控件 lbl_from.place(x=180,y=150) unitsecond.place(x=280,y=150) else: # 隐藏控件 lbl_from.place_forget() unitsecond.place_forget() # 绑定下拉框选中事件 unitfirst.bind("<<ComboboxSelected>>", on_unit_selected) main_frame.mainloop()
关键代码说明
place_forget():Tkinter控件的方法,用于隐藏控件(只是不显示,控件对象仍然存在)<<ComboboxSelected>>:ttk下拉框的选中事件,当用户选择不同选项时触发if-else逻辑:判断选中的单位类型,只有选中Volume时才显示第二个下拉框,其他情况都隐藏
内容的提问来源于stack exchange,提问作者user19499782
相关产品推荐
相关产品推荐

