简体   繁体   中英

Add value from drop down list to tkinter GUI once item is selected? Python

I have a list of items, I want aa user to select an item from the list. I have a command in the OptionValue code, I want to be able to display what they have selected on the GUI in a Label. Below is my following sample code. Not sure what I am missing. It is Python 3.4

from tkinter import *

class call(object):
    def __init__(self,name):
        self.name = name


    def func(self):
        Label(root, text ='Test'+var.get()).grid(row= 4,column = 3)



    def mke(self):

        global var
        global root
        root = Tk()
        options = ["1", "2", "3"]
        var = StringVar()
        OptionMenu(root, var, *options, command=call.func(self)).grid(row = 0,column = 3)

        mainloop()





a = call('')
a.mke()

command expects function name - without () and arguments.

If you use class then you could use self.var in place of global .

Your code looks strange so I made my own example

from tkinter import *

class Call(object): # CamelCase name for class

    def __init__(self, name):
        self.name = name

        root = Tk()
        options = ["1", "2", "3"]

        self.var = StringVar()

        self.label = Label(root, text='Test')
        self.label.grid(row=4, column=3)

        OptionMenu(root, self.var, *options, command=self.change_label).grid(row=0, column=3)

        root.mainloop()

    def change_label(self, event):
        self.label['text'] = 'Test ' + self.var.get()

a = Call('')

by the way:

command=call.func(self)

this means: run call.func(self) and result assigns to command=

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM