【问题标题】:Frame with no background in tkintertkinter 中没有背景的框架
【发布时间】:2020-11-01 19:12:31
【问题描述】:

我在 Tkinter 中有一个带有背景图像的画布。我想添加一个没有背景的框架,以便我可以在窗口中排列元素,但是,仍然可以看到这些元素背后的背景。当我使用类似于下面代码的东西时,即不指定背景颜色时,我得到一个灰色背景的框架。怎么把它变成无背景?

import tkinter as tk
from PIL import Image,ImageTk

root=tk.Tk()
root.geometry("800x560")

bgImg=Image.open("data/bg.png")
bgImg=ImageTk.PhotoImage(bgImg)
canvas=tk.Canvas(root,width=800,height=560)
canvas.pack(expand = False, fill = "both")

canvas.create_image(0, 0, image=bgImg, anchor="nw")

frame=tk.Frame(canvas,width=50,height=50)
frame.place(relx=0.5,rely=0.5,anchor="center")

root.mainloop()

【问题讨论】:

  • tkinter 小部件不支持透明背景。

标签: python python-3.x tkinter


【解决方案1】:

可能*有与平台相关的选项,例如this
(* 在 Lubuntu 18.04 和 python 3.6.9 中,它们似乎不起作用,
所以我无法测试它们。)

一个跨平台(?)选项是使用 Canvas。
然后在画布上绘制图像*,而不是使用小部件。
(*其 alpha 通道决定了它们的透明像素)
这将正确绘制前景/背景元素,
& Canvas 有足够的功能来控制上面的元素
(但如果您想模拟完整的小部件,则需要工作)。

Canvas 提供各种 create_xyz 方法,其中 xyz:
arclinerectanglebitmapovaltexttextimagepolygonwindow ( 这些返回一个 id,代表画布中的项目。
项目也可以分组关联,由标签表示。

* 在 Canvas 中使用小部件时,有一些限制:
https://tcl.tk/man/tcl8.6/TkCmd/canvas.htm#M163
"注意:由于窗口管理方式的限制,
无法绘制其他图形项目
(例如线条和图像)在窗口项目的顶部。
窗口项总是会遮盖与其重叠的任何图形,
无论它们在显示列表中的顺序如何。”

画布中的项目,可以配置并具有事件处理程序:
itemconfig / itemcget
tag_bind / tag_unbind
这些可以使用单独的 item-id 或* group-tag。
(* 尽管名称中有 'tag_',但它们也采用 item-ids)

许多其他 Canvas 方法都适用于 item-ids 或 group-tags
(例如movedelete、)。

import tkinter as tk

root = tk.Tk()

canvas = tk.Canvas(root, width=300, height=300)
canvas.pack()

# Note:
# If the images overlap exactly (same position & extent),
# the bottom one will never? get any events.
# Maybe events can be propagated, not sure right now.

fgImg = tk.PhotoImage(master=root, file='media/fg.png')
fgImgId = canvas.create_image(
  80, 80, anchor=tk.NW, image=fgImg
)
canvas.tag_bind(
  fgImgId,
  '<ButtonRelease-1>',
  lambda e: canvas.tag_raise(fgImgId)
)

bgImg = tk.PhotoImage(master=root, file='media/bg.png')
bgImgId = canvas.create_image(
  0, 0, anchor=tk.NW, image=bgImg
)
canvas.tag_bind(
  bgImgId,
  '<ButtonRelease-1>',
  lambda e: canvas.tag_raise(bgImgId)
)

root.mainloop()

还有更多关于此的 StackOverflow 问题,例如:
transparent-background-in-a-tkinter-window
python-tkinter-label-background-transparent
configure-tkinter-ttk-widgets-with-transparent-backgrounds-ttk-frame-background
等等。

您可能还想研究其他 gui 工具包。
(例如 wxpython*、pyqt、)
(*Here 它说,它有一个SetTransparent 命令。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 2019-06-14
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多