How can i create a drop-down menu in Tkinter?

I think it's called an OptionMenu ...

''' tk_OptionMenu1.py
using Tkinter's Optionmenu() as a combobox
allows one item to be selected
use a button to show selection
'''

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def ok():
    sf = "value is %s" % var.get()
    root.title(sf)
    root['bg'] = var.get()


root = tk.Tk()
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("%dx%d+%d+%d" % (330, 80, 200, 150))
root.title("tk.Optionmenu as combobox")

var = tk.StringVar(root)
# initial value
var.set('red')

choices = ['red', 'green', 'blue', 'yellow','white']
option = tk.OptionMenu(root, var, *choices)
option.pack(side='left', padx=10, pady=10)

button = tk.Button(root, text="check value slected", command=ok)
button.pack(side='left', padx=10, pady=10)

root.mainloop()

Thank you @vegaseat.

@vegaseat, look at line 29 of your code please. As you typed on the code, we need to have line 29 in our file from the beginning of running the program.
I mean i want to use load_choices for example instead of line 29. I want to load the choices list from a text file (my db file), and send it into() in lime 30.
What should i do?

No idea what your file looks like.

# let's assume your data is read from a file like this
data = '''\
red
green
blue
yellow
white
'''


choices = [color for color in data.split()]
print(choices)

''' result ...
['red', 'green', 'blue', 'yellow', 'white']
'''

This a the first part of my code:

import os
import pickle

DBFILENAME = 'linknames.db'
loaded = True
choices = []

def pathtofile(filename = DBFILENAME):
    folder = os.path.dirname(os.path.abspath(__file__))
    return os.path.join(folder, filename)


def load_choices():
    global choices, loaded
    if loaded:
        return
    filepath = pathtoile()
    if not os.path.isfile(filepath):
        with open(filepath, 'wb') as fout:
            pickle.dump([], fout)

    with open(filepath, 'rb') as fin:
        choices = pickle.load(fin)
    loaded = True

def dump_choices():
    filepath = pathtofile()
    with open(filepath, 'wb') as fout:
        pickle.dump(choices, fout)

import sqlite3 as db

conn = db.connect('linkuserpass.db')
cursor = conn.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS linkuserpass(mylink TEXT, myusername TEXT, mypassword TEXT)')
print ('table is created')
conn.commit()
cursor.close()
conn.close()



def add():
    import sqlite3 as db

    link = ent1.get()
    user = ent2.get()
    password = ent3.get()

    conn = db.connect('linkuserpass.db')
    cursor = conn.cursor()
    cursor.execute('INSERT INTO linkuserpass(mylink, myusername, mypassword) VALUES(?,?,?)', (link, user, password))
    print ('Done!')
    conn.commit()
    cursor.close()
    conn.close()

    load_choices()
    choices.append(ent1.get())
    dump_choices()


def show():
    import sqlite3 as db

    key_link = var.get()

    conn = db.connect('linkuserpass.db')
    conn.row_factory = db.Row
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM linkuserpass WHERE mylink=(?)' , (key_link,))
    row = cursor.fetchone()
    data_str1 = ""
    data_str2 = ""
    data_str1 = (row['myusername'])
    data_str2 = (row['mypassword'])
    print data_str1
    print data_str2
    userlabel['text'] = 'username:  ' + data_str1
    passwordlabel['text'] = data_str2
    conn.commit()
    cursor.close()
    conn.close()

And the rest is the Tkinter code part. Look at this please:

var = StringVar(root)
var.set('')

load_choices()
option = OptionMenu(root, var, choices)
option.pack()

btn2 = Button(frame5, text = 'show', command = show)
btn2.pack(side = 'left')

With load_choices that i have typed, when i run the program, no value will be shown on the option menue, its empty.
What should i do?

Make sure the data is presented to the OptionMenu() as a list that is unpacked with the * operator. Testprint choices and use *choices as an argument.

commented: Sharp +12
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.