我试着做一种“表格”,一边是图像和文本,另一边是tabel上每一行旁边的复选按钮。tabel应该有两列。我所做的是创建一个tabel类,并用两个帧将其旋转。问题是,当我标记一个按钮时,他的另一个也会被标记
******编辑: 好吧,我在试着给所有的按钮做标记时意外地解决了这个问题 在下面的代码中添加了标记行,它解决了这个问题,但我不知道为什么。我很乐意得到解释(markes as****new)
图像:
之前:
之后:
代码:
from tkinter import *
from PIL import Image, ImageTk
class Example(Frame):
def __init__(self, root, side):
Frame.__init__(self, root)
self.root = root
*******new: self.ver_list = [IntVar(value=1) for i in range(1, 202)]
self.vsb = Scrollbar(self, orient="vertical")
self.text = Text(self, width=40, height=20,
yscrollcommand=self.vsb.set)
self.im = Image.open("pic.png")
self.tkimage = ImageTk.PhotoImage(self.im)
self.vsb.config(command=self.text.yview)
self.vsb.pack(side="{}".format(RIGHT if side else LEFT), fill="y")
self.text.pack(side="left", fill="both", expand=True)
if side:
for i in range(1, 101):
cb = Checkbutton(self, text="checkbutton #%s" % i, indicatoron=True, image=self.tkimage, compound=LEFT)
cb.config(font=("Courier", 15))
new***: self.cb.config(variable=self.ver_list[i])
self.text.window_create("end", window=cb)
self.text.insert("end", "\n") # to force one checkbox per line
else:
for i in range(101, 201):
cb = Checkbutton(self, text="checkbutton #%s" % i, indicatoron=True, image=self.tkimage, compound=LEFT)
cb.config(font=("Courier", 15))
new***: self.cb.config(variable=self.ver_list[i])
self.button_list.append(cb)
self.text.window_create("end", window=cb)
self.text.insert("end", "\n") # to force one checkbox per line
if __name__ == "__main__":
root = Tk()
frame1 = Frame(root)
frame2 = Frame(root)
Example(frame1, 0).pack(side="top", fill="both", expand=True)
Example(frame2, 1).pack(side="top", fill="both", expand=True)
frame1.grid(row=0, column=0)
frame2.grid(row=0, column=1)
root.mainloop()
尝试
print(cb["variable"])
在旧版本中,您将看到两个具有相同ID的变量-!checkbutton
与
!checkbutton2
、!checkbutton3
等相同因此,第一个
Example()
创建具有一些默认名称的局部变量,但是第二个Example()
也创建具有默认名称的局部变量,但是它不知道这些名称已经存在这样,两个复选按钮使用相同名称的变量
在新代码中,您使用202
IntVar
创建列表,它们具有唯一的ID,因此每个Checkbutton
都使用具有唯一ID的变量相关问题 更多 >
编程相关推荐