Advertisement
here2share

# ttk_optionmenu_bug_fix_demo.py

Sep 17th, 2024
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.29 KB | None | 0 0
  1. # ttk_optionmenu_bug_fix_demo.py
  2.  
  3. import tkinter as tk
  4. from tkinter import StringVar
  5. from tkinter import ttk
  6. import string
  7.  
  8. sss = string.ascii_uppercase
  9.  
  10. root = tk.Tk()
  11. root.title("ttk.OptionMenu Demo")
  12.  
  13. def clear_and_disable():
  14.     for i, option_menu, _ in option_menus:
  15.         var[i].set("")
  16.         option_menu['menu'].delete(0, 'end')
  17.         option_menu.state(["disabled"])
  18.  
  19. def populate_and_enable():
  20.     for i, option_menu, options in option_menus:
  21.         for option in options:
  22.             option_menu['menu'].add_command(label=option, command=lambda opt=option, i=i: var[i].set(opt))
  23.         option_menu.state(["!disabled"])
  24.         var[i].set(options[0])
  25.  
  26. var = {}
  27. option_menus = []
  28. for i in range(0, 5):
  29.     var[i] = StringVar(root)
  30.     options = [f"Option {sss[i+(j*5)]}" for j in range(5)]
  31.     option_menu = ttk.OptionMenu(root, var[i], *[options[0]] + options) # *[options[0]] + options fixes an OptionMenu bug
  32.     option_menu.pack(pady=3)
  33.     option_menus.append((i, option_menu, options))
  34.     var[i].set(options[0])
  35.  
  36. clear_button = tk.Button(root, text="Clear and Disable", command=clear_and_disable)
  37. clear_button.pack(fill='x')
  38.  
  39. enable_button = tk.Button(root, text="Populate and Enable", command=populate_and_enable)
  40. enable_button.pack(fill='x')
  41.  
  42. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement