使用“ComboboxSelected”的一个功能来读取多个组合框

时间:2016-12-31 07:33:55

标签: python tkinter

我正在尝试为多个组合框使用相同的选择事件;可能吗?我找不到传递给函数的方法,即事件的发送者。

    def newselection(self, event, {????}):
        self.selection = self.{????}.get()
        print(self.selection)

    self.combo1 = Combobox(self, width=7)
    self.combo1.bind("<<ComboboxSelected>>", self.newselection({????}))
    self.combo1['values'] = ('a', 'c', 'g', 't')
    self.combo1.place(x=250, y=400)
    self.combo1.state(['readonly'])

    self.combo2 = Combobox(self, width=7)
    self.combo2.bind("<<ComboboxSelected>>", self.newselection({????}))
    self.combo2['values'] = ('X', 'Y', 'XX', 'XY')
    self.combo2.place(x=450, y=400)
    self.combo2.state(['readonly'])

所以选择哪个组合并不重要,我可以使用相同的功能并读取发送者,这样我就可以正确分配组合框的值。

1 个答案:

答案 0 :(得分:3)

bind需要函数名称 - 它表示没有()和参数。但它使用event执行此功能,可以访问小部件 - event.widget

工作示例:

import tkinter as tk
from tkinter import ttk

# --- functions ---

def newselection(event):
    print('selected:', event.widget.get())

# --- main ---

root = tk.Tk()

cb1 = ttk.Combobox(root, values=('a', 'c', 'g', 't'))
cb1.pack()
cb1.bind("<<ComboboxSelected>>", newselection)

cb2 = ttk.Combobox(root, values=('X', 'Y', 'XX', 'XY'))
cb2.pack()
cb2.bind("<<ComboboxSelected>>", newselection)

root.mainloop()

如果您需要更多参数,则必须使用lambda

import tkinter as tk
from tkinter import ttk

# --- functions ---

def newselection(event, other):
    print('selected:', event.widget.get())
    print('other:', other)

# --- main ---

root = tk.Tk()

cb1 = ttk.Combobox(root, values=('a', 'c', 'g', 't'))
cb1.pack()
cb1.bind("<<ComboboxSelected>>", lambda event:newselection(event, "Hello"))

cb2 = ttk.Combobox(root, values=('X', 'Y', 'XX', 'XY'))
cb2.pack()
cb2.bind("<<ComboboxSelected>>", lambda event:newselection(event, "World"))

root.mainloop()