[英]Tkinter Canvas create_window function does not show the desired widgets
我试图为我的应用程序制作一个自定义容器 function,但是当我传递小部件列表时,它们不可见。 容器类似于LabelFrame
,但带有圆角。 我尝试了很多东西,但似乎没有任何效果。 请让我知道我做错了什么。
这是我的代码和一些评论:
parent
-> 这是顶层 window
lbl_text
-> 这将是LabelFrame
顶部的小文本
widgets
-> 这是我想放置在圆形框架中的小部件列表
def rndframe(parent, lbl_text, widgets
# content_positioner and max_width is for calculate the requiered size of the canvas to be big
# enough for all the passed widgets, and to determine the coordinates for create_window function.
# It works perfectly and I get all the information I want.
content_positioner = [14]
max_width = 1
for i, item in enumerate(widgets):
content_positioner.append(content_positioner[i]+widgets[i].winfo_reqheight())
if widgets[i].winfo_reqwidth() > max_width:
max_width = widgets[i].winfo_reqwidth()
height = max(content_positioner)+10
width = max_width+10
# Here I create the canvas which will contain everything
canv = TK.Canvas(parent, height=height, width=width, bg='green', bd=0, highlightthickness=0)
# Here I draw the rounded frame
radius = 10
x1 = 2
y1 = 5
x2 = width-2
y2 = height-2
points = [x1+radius, y1, x2-radius, y1, x2, y1, x2, y1+radius, x2, y2-radius, x2, y2,
x2-radius, y2, x1+radius, y2, x1, y2, x1, y2-radius, x1, y1+radius, x1, y1]
canv.create_polygon(points, smooth=True, outline=DS.menu_bg, width=3, fill='')
# Here I put the litle label in the frmae
label = TK.Label(parent, text=lbl_text, bg=DS.main_bg, padx=3, pady=0, fg=DS.main_textcolor)
canv.create_window(18, 5, anchor='w', window=label)
# And thats the part where I would like to place all the passed widgets based on the coordinate
# list I preveously created but nothing appear just the frame polygon and the liitle label on it.
for w, widget in enumerate(widgets):
canv.create_window(width/2, content_positioner[w], anchor='n', window=widgets[w])
return canv
最后是我尝试使用的方式:
id_num = TK.Label(result_area_leaf, text='123-4567')
id_num2 = TK.Label(result_area_leaf, text='123-4567')
id_holder = rndframe(result_area_leaf, lbl_text='id', widgets=[id_num, id_num2])
id_holder.grid()
您的代码有很多问题,但问题的根源是您添加到 canvas 的小部件的堆叠顺序低于 canvas,因此它们位于 canvas 的后面或“下方”。这是因为默认堆叠顺序最初由小部件的创建顺序决定。 您在 canvas 之前创建小部件,因此它们的堆叠顺序较低。
堆叠顺序问题的最简单解决方案是将小部件提升到 canvas 以上,您可以使用lift
方法来完成。
for w, widget in enumerate(widgets):
canv.create_window(width/2, content_positioner[w], anchor='n', window=widgets[w])
widgets[w].lift()
当我进行上述修改并修复代码中的所有其他问题时,标签出现在 canvas 中。
最后我得到它的工作。 首先很抱歉我没有首先发布独立的可运行代码。 当我将代码放入文件中并对缺失的变量进行必要的更改时,建议的.lift()
方法起作用了。 原因是在那个单个文件中,我使用根目录 window 作为父目录。
在我复制的代码中,两个标签( id_num
和id_num2
)有一个 Canvas 用于父级(result_area_leaf),这就是问题所在。 如果我将我的根 window 作为传递的小部件的父级,则会显示这些小部件。 .lift()
实际上根本不需要。
谢谢你们;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.