[Python] tkinter Combobox onchange

要存取 combobox 的 onselected 事件,請使用下面範例:

bind <> to a method…

import tkinter as tk
from tkinter import ttk

class Main(tk.Tk):

  def __init__(self, *args, **kwargs):
    tk.Tk.__init__(self, *args, **kwargs)
    self.container = tk.Frame(self)
    self.container.pack(side="top", fill = "both", expand=True)
    self.container.grid_rowconfigure(0, weight=1)
    self.container.grid_columnconfigure(0, weight=1)
    self.cb=ttk.Combobox(self.container, values=[0,1, 2, 3] , state='readonly')
    self.cb.bind('<<ComboboxSelected>>', self.modified)    
    self.cb.pack()

  def modified (self, event) :
      print(self.cb.get())

main = Main()
main.mainloop()

範例2號:

import tkinter as tk
from tkinter import ttk

def callbackFunc(event):
     print("New Element Selected")
     
app = tk.Tk() 
app.geometry('200x100')

labelTop = tk.Label(app,
                    text = "Choose your favourite month")
labelTop.grid(column=0, row=0)

comboExample = ttk.Combobox(app, 
                            values=[
                                    "January", 
                                    "February",
                                    "March",
                                    "April"])


comboExample.grid(column=0, row=1)
comboExample.current(1)

comboExample.bind("<<ComboboxSelected>>", callbackFunc)


app.mainloop()

範例2號的資料來源:
https://github.com/DelftStack/DelftStack/blob/master/Tutorial/Tkinter/Tkinter%20Combobox_Virtual%20Event%20Binding.py

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *