Tkinter语言 - 在(以交互方式)向其添加元素后扩展框架



我有以下代码:

from tkinter import *

DEF_CHANNELS = {'iris': (255, 0, 0), 'sclera': (0, 255, 0), 'pupil': (0, 0, 255)}

class GUI(Tk):
def __init__(self, init_source, init_target, *args, **kw):
super().__init__(*args, **kw)
self.frame = Frame(self, height=400, width=500)
self.frame.pack(fill=BOTH, expand=YES)
self.channel_frame = Frame(self.frame, height=200, width=500, pady=16)
self.channel_frame.grid(column=0, row=0, columnspan=2)
self.channel_label = Label(self.channel_frame, text="Channel")
self.channel_label.grid(column=0, row=0)
self.colour_label = Label(self.channel_frame, text="Colour")
self.colour_label.grid(column=1, row=0)
self.channel_frames = []
for channel, colour in DEF_CHANNELS.items():
self.add_channel_frame(channel, colour)
self.channel_button = Button(self.channel_frame, text="+", command=self.add_channel_frame)
self.channel_button.grid(column=0, row=len(self.channel_frames) + 1)
def add_channel_frame(self, def_channel="", def_colour=""):
pair_frame = ChannelColourFrame(self.channel_frame, def_channel=def_channel, def_colour=def_colour, height=100, width=500, pady=2)
pair_frame.grid(column=0, row=len(self.channel_frames) + 1, columnspan=2)
self.channel_frames.append(pair_frame)

class ChannelColourFrame(Frame):
def __init__(self, *args, def_channel="", def_colour="", **kw):
super().__init__(*args, **kw)
self.channel_txt = Entry(self, width=30)
self.channel_txt.insert(END, def_channel)
self.channel_txt.grid(column=0, row=0)
self.colour_txt = Entry(self, width=30)
self.colour_txt.insert(END, def_colour)
self.colour_txt.grid(column=1, row=0)
self.color_picker_button = Button(self, text="u2712")
self.color_picker_button.grid(column=2, row=0)
self.remove_button = Button(self, text="-", command=self.remove)
self.remove_button.grid(column=3, row=0)
def remove(self):
self.master.master.master.channel_frames.remove(self)
self.destroy()
gui = GUI('', '')
gui.mainloop()

这个想法是有一个以 3 个默认文本Entry对开头的Frame,用户可以任意删除/添加。在大多数情况下,它工作正常,但有一个大问题。框架(self.channel_frame(永远不会膨胀超过其初始高度,当超过最初的3个Entry对出现在它上面时,这会导致问题。

如何使整个Frame在每次删除/添加Entry对时都适合

?作为一个附加问题,u2712在我的按钮上显示为一个框,但它应该是黑色笔尖符号(✒(。为什么尽管是 unicode 的一部分,但符号没有显示?

您不会创建任何新行,因此它不会增长。开始时,创建三个通道帧,并将它们放在第 0、1 和 2 行中。然后,在第 4 行中添加"+"按钮。

当您单击"+"按钮时,它会在len(self.channel_frames) + 1处添加一个新行。由于len(self.channel_frames)是 3,因此它会在第 4 行添加新帧,该帧位于"+"按钮的顶部。因此,您不会添加新行。

如果将"+"按钮移出框架,或者在每次添加新行时将其向下移动,则代码工作正常。

例如:

def add_channel_frame(self, def_channel="", def_colour=""):
pair_frame = ChannelColourFrame(self.channel_frame, def_channel=def_channel, def_colour=def_colour, height=100, width=500, pady=2)
pair_frame.grid(column=0, row=len(self.channel_frames) + 1, columnspan=2)
self.channel_frames.append(pair_frame)
self.channel_button.grid(column=0, row=len(self.channel_frames)+1)

作为一个附加问题,\u2712 在我的按钮上显示为一个框,但它应该是黑色笔尖符号 (✒(。为什么尽管是 unicode 的一部分,但符号没有显示?

可能是因为您使用的字体没有该符号。尝试使用其他字体。

最新更新