1

Import a tkinter OptionMenu who's background colour changes based on selection.

The below code creates a tkinter OptionMenu whos background colour changes based on the selection chosen from the dropdown menu. It works as I want it too as is.

But, how do I make this OptionMenu re-usable? So that I can import it into my main .py file from a different .py file.

I've been trying different things and reading for days about how to do this and haven't been able to figure it out. I've read about turning functions into classes and variables into functions etc. and importing those. However, I have been unable t get it quite right and am stumped.

import tkinter

HEIGHT = 700
WIDTH = 1100

m = tkinter.Tk()
from lists import lbmenuopt

canvas = tkinter.Canvas(m, height=HEIGHT, width=WIDTH,)
canvas.pack()

#selected item variable
clicked1 = tkinter.StringVar()

# function that changes background color based on selection
def lbmenubg(clicked1):
    if clicked1 == "---":
        lbmenu.configure(bg="#777777", activebackground="#777777")
    elif clicked1 == "LB":
        lbmenu.configure(bg="#D35400", activebackground="#D35400")
    elif clicked1 == "Sign":
        lbmenu.configure(bg="#D35400", activebackground="#D35400")
    else:
        lbmenu.configure(bg="#196F3D", activebackground="#196F3D")

# Option Menu settings and placement
lbmenu = tkinter.OptionMenu(m, clicked1, *lbmenuopt, command= lambda x: lbmenubg(clicked1.get()))

lbmenu.config(bg="#777777", foreground="white", activeforeground="white", activebackground="#777777",
              borderwidth=0, relief="flat", bd=0)

lbmenu['menu'].config(bg="#e4e4e4", fg="black", activebackground="white", activeforeground="#3b4045",)

lbmenu.place(relx=0.125, rely=.03, relwidth=0.065, relheight=0.03)

m.mainloop()
Conor
  • 11
  • 2
  • 1
    Make this as a class and create instance whenever you want to use it again – Prudhvi Nov 14 '19 at 03:17
  • 1
    ***"make this `OptionMenu` re-usable? "***: It is defined as `class OptionMenu`, therefore you can can create your own `BackgroundOptionMenu(tk.OptionMenu):` by inheritance. See [option-from-optionmenu-into-a-variable-for-further-use](https://stackoverflow.com/a/52869393/7414759) or [Show only the filename in OptionMenu](https://stackoverflow.com/a/58000626/7414759) – stovfl Nov 14 '19 at 10:12

0 Answers0