下面的代码测试是可以的,主要是通过window.wm_attributes('-transparentcolor', 'white')将主窗口的白色设置为透明色,然后再指定Canvas的背景色为白色且边框为0就可以实现背景透明了,但是背景图片里面不能有白色,不然也会透明(可以稍微调节一下RGB,比如改成254,254,254实现接近白色的效果)
通过设置window.overrideredirect(True)去除窗口标题及边框
[Java] 纯文本查看 复制代码 import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
def open_folder():
folder_path = filedialog.askdirectory()
folder_path_var.set(folder_path)
# 创建窗口
window = tk.Tk()
window.title("Open Folder")
window.overrideredirect(True)
window.wm_attributes('-transparentcolor', 'white')
# 打开并设置背景图像
background_image = Image.open("bg.PNG")
background_photo = ImageTk.PhotoImage(background_image)
# 创建画布并添加背景图像
canvas = tk.Canvas(window, width=background_image.width, height=background_image.height, bg="white", highlightthickness=0)
canvas.pack()
canvas.create_image(0, 0, anchor=tk.NW, image=background_photo)
# 创建文本框并将其放置在画布上
folder_path_var = tk.StringVar()
folder_path_entry = tk.Entry(window, textvariable=folder_path_var)
canvas.create_window(300, 200, window=folder_path_entry)
# 创建按钮并将其放置在画布上
open_button = tk.Button(window, text="Open", command=open_folder)
canvas.create_window(300, 350, window=open_button)
# 计算窗口居中位置
window_width = window.winfo_reqwidth()
window_height = window.winfo_reqheight()
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
x_coordinate = (screen_width // 2) - (window_width // 2)
y_coordinate = (screen_height // 2) - (window_height // 2)
# 设置窗口在屏幕上的位置(居中)
window.geometry(f'+{x_coordinate}+{y_coordinate}')
# 运行主循环
window.mainloop()
|