Search code examples
pythontkintercombobox

Restart the Combobox tkinter after clicking a button


I'm new to Python and Tkinter. I'm following Python + MySQL. How can I pass the ID of a field from a ComboBox to the database? as a guideline to get the value by index. When I click Submit button, the Combobox still shows the previous value.

My Code:

import tkinter as tk
from tkinter import ttk

def data_set(index):
    index = cb.current()
    data.set(c[index][0])
    
c = [
  (123, 'A'),
  (124, 'B'),
  (125, 'C'),
]

def clear():
  print(data.get())
  # I need the Combobox shows an empty value before clicking the dropdown button.
  
root = tk.Tk()
data = tk.StringVar()

cb = ttk.Combobox(root,values=[row[1] for row in c], state='readonly')
cb.pack()
cb.bind("<<ComboboxSelected>>", data_set)

btn = tk.Button(root, text="Submit",command=clear)
btn.pack()

root.mainloop()

The output when choosing A and clicking the Submit button:

123

But The Combobox still displays the previous value:

Still display the previous value

I'm looking for a way like after choosing A and clicking the Submit button, the output of 123 print to terminal, then the Combobox go back to the beginning like below:

The combobox go back to the beginning

Please help me. Thank you so much.


Solution

  • if you would use StringVar with textvariable in Combobox then you could set empty string in StringVar to reset Combobox

    import tkinter as tk
    from tkinter import ttk
    
    c = [
      (123, 'A'),
      (124, 'B'),
      (125, 'C'),
    ]
    
    def clear():
        index = cb.current()
        print(data.get())    # A
        print(c[index][0])   # 123
        data.set('')         # reset
    
    root = tk.Tk()
    data = tk.StringVar(root)
    
    cb = ttk.Combobox(root, textvariable=data, values=[row[1] for row in c], state='readonly')
    cb.pack()
    
    btn = tk.Button(root, text="Submit", command=clear)
    btn.pack()
    
    root.mainloop()