Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More concise way to configure tkinter option menu?

I am a beginner in python, normally if i want to add option menu to my program, i would do something like this.

from Tkinter import*
root=Tk()

mylist=['a','b','c']
var=StringVar(root)
var.set("Select status")
mymenu=OptionMenu(root,var,*mylist)
mymenu.pack()
mymenu.config(font=('calibri',(10)),bg='white',width=12)
mymenu['menu'].config(font=('calibri',(10)),bg='white')

root.mainloop()

It works fine but i am wondering if there is any shorter way to achieve the same result as each option menu will take 7 lines of code. I have to create several option menu so i am looking for a proper and shorter way to do it.

EDIT: Someone pointed out to create function that will generate option menu. So i tried this,

from Tkinter import*

def Dropmenu(mylist,status):
    var=StringVar(root)
    var.set(status)
    mymenu=OptionMenu(root,var,*mylist)
    mymenu.pack(side=LEFT)
    mymenu.config(font=('calibri',(10)),bg='white',width=12)
    mymenu['menu'].config(font=('calibri',(10)),bg='white')

root=Tk()

Dropmenu(['a','b','c'],'Select')

root.mainloop()

But now, how do i address the "var" so that i can fetch all the values that user chose? According to my example, all the option menu will have the same "var" value, so i have no way to get the choices that user made for different option menu.

To make things more clear,let's say if i have 2 option menu

Dropmenu(['a','b','c'],'Select')
Dropmenu(['c','d','e'],'Select')

If i use

myvalue=var.get()

Since both option menus have the same var name, how do i fetch the both values?

like image 600
Chris Aung Avatar asked Mar 23 '23 14:03

Chris Aung


1 Answers

If you are going to create several menus with the same configuration, I would subclass OptionMenu instead of defining a function:

from Tkinter import*

class MyOptionMenu(OptionMenu):
    def __init__(self, master, status, *options):
        self.var = StringVar(master)
        self.var.set(status)
        OptionMenu.__init__(self, master, self.var, *options)
        self.config(font=('calibri',(10)),bg='white',width=12)
        self['menu'].config(font=('calibri',(10)),bg='white')

root = Tk()
mymenu1 = MyOptionMenu(root, 'Select status', 'a','b','c')
mymenu2 = MyOptionMenu(root, 'Select another status', 'd','e','f')
mymenu1.pack()
mymenu2.pack()
root.mainloop()

In my example, I have supposed the only thing that is going to change is the options, but if each instance has its own background color or font, then you only have to add it as an argument to the __init__ method.

like image 84
A. Rodas Avatar answered Apr 01 '23 16:04

A. Rodas