gpt4 book ai didi

在 for 循环中创建的组合框中的 python tkinter 引用

转载 作者:行者123 更新时间:2023-12-04 16:49:13 26 4
gpt4 key购买 nike

我的代码到目前为止,我想根据comboboxselection 导入图像。我需要引用 self.box。例如self.box1、self.box2 等,或者如果可能的话将它们附加到循环的某处

from Tkinter import *
import ttk


class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master, relief="sunken", border=1)
self.master = master
self.grid()
self.create_widgets()

def create_widgets(self):
for i in range(9):
self.box = ttk.Combobox(self, state="readonly")
self.box["values"] = ("apple", "bannana", "cherry", "raspberry", "blueberry", "lemon", "tomato", "potato",
"None")
self.box.grid(row=1+i, column=2, pady=1, padx=1, sticky=E+W+N+S)
self.box.current(i)
self.box.bind("<<ComboboxSelected>>", self.change_icon)
print self.box["values"][i]


def change_icon(self, event):
self.var_Selected = self.box.current()
print "The user selected value now is:"
print self.var_Selected

root = Tk()
root.title("Random title")
root.geometry("500x250")
app = Application(root)
root.mainloop()

最佳答案

您可以让您的应用程序保留一个字典对象(或一个列表,但实现高度依赖于索引),将您的框存储在以 i 为键的字典中:

class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master, relief="sunken", border=1)
# Various initialization code here
self.box_dict = {}

def create_widgets(self):
for i in range(9):
box = ttk.Combobox(self, state="readonly")
# Do various things with your box object here
self.box_dict[i] = box
# Only complication is registering the callback
box.bind("<<ComboboxSelected>>",
lambda event, i=i: self.change_icon(event, i))


def change_icon(self, event, i):
self.var_Selected = self.box_dict[i].current()
print "The user selected value now is:"
print self.var_Selected

然后通过 self.box_dict[0] 等访问框

编辑 我对 bindchange_icon 方法进行了更新,让每个框将其索引号发送到 change_icon 当事件被触发时。Edit2 将实现更改为使用 dict 而不是 list,这看起来更可靠。

关于在 for 循环中创建的组合框中的 python tkinter 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28736028/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com