2013-07-10 17 views
9

Dire che ho un menu di opzioni network_select che ha un elenco di reti a cui connettersi.Modifica delle opzioni di un Menu Opzione quando si fa clic su un pulsante

import Tkinter as tk 

choices = ('network one', 'network two', 'network three') 
var = tk.StringVar(root) 
network_select = tk.OptionMenu(root, var, *choices) 

Ora, quando l'utente preme il pulsante di aggiornamento, desidero aggiornare l'elenco di reti a cui l'utente può connettersi.

  • io non posso usare .config perché ho guardato attraverso network_select.config() e non ho visto una voce che sembrava che le scelte ho dato.
  • Non penso che questo sia qualcosa che si può cambiare usando una variabile tk, perché non esiste una cosa come ListVar.
+0

Che dire rendendolo una variabile oggetto? – KingJohnno

risposta

19

ho modificato lo script per dimostrare come fare questo:

import Tkinter as tk 

root = tk.Tk() 
choices = ('network one', 'network two', 'network three') 
var = tk.StringVar(root) 

def refresh(): 
    # Reset var and delete all old options 
    var.set('') 
    network_select['menu'].delete(0, 'end') 

    # Insert list of new options (tk._setit hooks them up to var) 
    new_choices = ('one', 'two', 'three') 
    for choice in new_choices: 
     network_select['menu'].add_command(label=choice, command=tk._setit(var, choice)) 

network_select = tk.OptionMenu(root, var, *choices) 
network_select.grid() 

# I made this quick refresh button to demonstrate 
tk.Button(root, text='Refresh', command=refresh).grid() 

root.mainloop() 

Non appena si fa clic sul pulsante "Aggiorna", le opzioni in network_select vengono cancellati e quelli in new_choices sono inseriti.

+0

Per curiosità, dov'è il 'network_select ['menu']'? – charmoniumQ

+0

@Sam: È qui dentro: network_select.keys() – iCodez

+0

Grazie! Ogni widget di Tkinter ha un '.keys()'? 'help (network_select ['menu'])' è quello di cui avevo bisogno! – charmoniumQ

0

Lo stesso, ma con tk.Menu widget

# Using lambda keyword and refresh function to create a dynamic menu. 
import tkinter as tk 

def show(x): 
    """ Show menu items """ 
    var.set(x) 

def refresh(l): 
    """ Refresh menu contents """ 
    var.set('') 
    menu.delete(0, 'end') 
    for i in l: 
     menu.add_command(label=i, command=lambda x=i: show(x)) 

root = tk.Tk() 
menubar = tk.Menu(root) 
root.configure(menu=menubar) 
menu = tk.Menu(menubar, tearoff=False) 
menubar.add_cascade(label='Choice', menu=menu) 

var = tk.StringVar() 
l = ['one', 'two', 'three'] 
refresh(l) 
l = ['four', 'five', 'six', 'seven'] 
tk.Button(root, text='Refresh', command=lambda: refresh(l)).pack() 
tk.Label(root, textvariable=var).pack() 
root.mainloop() 
Problemi correlati