我有两个组合框,我想根据另一个框中的值更新其中一个组合框的值。这是我的代码:
import tkinter as tk
import tkinter.ttk as ttk
def update_box(imagesbox, new_values):
imagesbox["values"] = new_values
def update_combobox_data(imagesbox, filterbox):
new_values = []
if filterbox.get() == "Bilateral":
new_values = ["Original", "Contours", "Bilateral", "Enhanced", "Greyscale", "Black and white"]
if filterbox.get() == "Median":
new_values = ["Original", "Contours", "Median", "Enhanced", "Greyscale", "Black and white"]
elif filterbox.get() == "Gaussian":
new_values = ["Original", "Contours", "Gaussian", "Enhanced", "Greyscale", "Black and white"]
imagesbox.set("")
update_box(imagesbox, new_values)
def labelframe(root, text, row, col):
label_frame = tk.LabelFrame(root, text=text)
label_frame.grid(row=row, column=col, padx=15, pady=10)
return label_frame
def label(root, text, row, col):
lab = tk.Label(root, text=text)
lab.grid(row=row, column=col, padx=15, pady=10)
return lab
def combobox(root, values, row, col):
box1 = ttk.Combobox(root, values=values, state="readonly")
box1.grid(row=row, column=col, padx=15, pady=10)
box1.set(values[0])
return box1
def main():
root = tk.Tk()
root.geometry("500x300")
frame = tk.Frame(root)
frame.pack()
labelframe1 = labelframe(frame, "Settings", 1, 0)
label1 = label(labelframe1, "Choose filter", 0, 0)
filters = ["Bilateral", "Median", "Gaussian"]
filter_combobox = combobox(labelframe1, filters, 1, 0)
label2 = label(labelframe1, "Image type", 0, 1)
images = ["Original", "Contours", "Bilateral", "Enhanced", "Greyscale", "Black and white"]
images_combobox = combobox(labelframe1, images, 1, 1)
bind1 = lambda: update_combobox_data(images_combobox, filter_combobox)
images_combobox.bind("<<ComboboxSelected>>", bind1)
root.mainloop()
main()
当我选择过滤器时,我希望图像类型框能够更新,以便过滤器在那里更新。例如,如果我选择高斯滤镜,则图像类型应为原始、轮廓、高斯、增强、灰度和黑白。但是,该框并未更新。我找到了某种解决方案,并且在我的代码中尝试进行类似的实现,但它不起作用。
此外,如果我更改图像类型,我会收到这个奇怪的错误:
TypeError: main.<locals>.<lambda>() takes 0 positional arguments but 1 was given
。我尝试从网上搜索,但不明白为什么会出现此错误。我找到了 this 答案,但我的 lambda 函数不接受任何参数,所以应该不会有问题?
我该如何修复这些错误?
对您的代码进行以下更改对我有用。
问题涉及绑定事件和错误的组合框调用。
将某些操作绑定到函数会传递
event
因此,将 update_combobox
更改为包含 event
def update_combobox_data(event, imagesbox, filterbox)
然后更改bind1以包含事件
bind1 = lambda event: update_combobox_data(event, images_combobox, filter_combobox)
还将
filter_combobox
绑定到bind1
filter_combobox.bind("<<ComboboxSelected>>", bind1)