Search code examples
pythontkintercombobox

Gettting element from combobox problem in tkinter


I am trying to get the selected element from combobox in tkinter. I will use this selected element in my code. There are some asked questions and posts in internet but they did not help me. So, I am sharing the related part of my code :

     self.dugme2 = Button(text="printer", command=self.ekle, fg="black", bg="green", font="bold")
     self.dugme2.place(relx=0.40,rely=0.65)

     self.ip_list2 = ttk.Combobox(width=15,state="readonly")
     self.ip_list2["values"] = ["eth0", "wan0","wan1"]
     self.ip_list2.place(relx=0.60, rely=0.08)
     self.ip_list2.set("Interfaces")
     self.selected_interf=self.ip_list2.get()

In the foregoing code, I tried to get the selected element using self.selected_interf=self.ip_list2.get(). After that, I wanted to print it in the screen using button and following function by

   def ekle(self):
     self.etiket3 = Label(text=self.selected_interf, font="Times 11 bold", bg="grey")
     self.etiket3.place(rely=0.78, relx=0.39)

I want to print the selected element in the combobox on the label when i click on the button

Can you help, please ?


Solution

  • You should call self.selected_interf=self.ip_list2.get() inside ekle() instead. Also it is better to create label self.etiket3 once and update its text inside ekle():

            self.dugme2 = Button(text="printer", command=self.ekle, fg="black", bg="green", font="bold")
            self.dugme2.place(relx=0.40, rely=0.65)
    
            self.ip_list2 = ttk.Combobox(width=15, state="readonly")
            self.ip_list2["values"] = ["eth0", "wan0", "wan1"]
            self.ip_list2.place(relx=0.60, rely=0.08)
            self.ip_list2.set("Interfaces")
    
            # create the label here instead of inside `ekle()`
            # initially it is hidden
            self.etiket3 = Label(font="Times 11 bold", bg="grey")
    
        def ekle(self):
            # get selection of combobox here
            self.selected_interf = self.ip_list2.get()
            # update label and show it
            self.etiket3.config(text=self.selected_interf)
            self.etiket3.place(rely=0.78, relx=0.39)