如何在带背景图的Tkinter界面中实现输入框与按钮透明化?
Tkinter登录界面透明输入框与按钮实现方案
问题根源
你当前代码中使用了白色背景的login_frame,所有输入框、按钮都嵌套在这个Frame内,因此无论怎么设置控件的透明属性,都会被Frame的白色背景遮挡,这是无法显示背景图的核心原因。
解决方案
我们通过移除白色Frame+使用Canvas承载背景与控件+透明色适配的方式实现视觉上的透明效果,以下是修改后的完整代码:
import tkinter as tk from tkinter import messagebox import sqlite3 from PIL import Image, ImageTk # Pillow库导入 def setup_database(): conn = sqlite3.connect("todo_app.db") cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, password TEXT NOT NULL ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS tasks ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, task TEXT NOT NULL, completed BOOLEAN NOT NULL DEFAULT 0, FOREIGN KEY(user_id) REFERENCES users(id) ) """) conn.commit() conn.close() def login_screen(): def login(): username = username_entry.get() password = password_entry.get() conn = sqlite3.connect("todo_app.db") cursor = conn.cursor() cursor.execute("SELECT id FROM users WHERE username = ? AND password = ?", (username, password)) user = cursor.fetchone() conn.close() if user: messagebox.showinfo("Başarılı", "Hoşgeldiniz Lordum!") root.destroy() # 关闭登录窗口 main_screen(user[0]) else: messagebox.showerror("Hata", "Kullanıcı adı veya şifre yanlış!") def register(): username = username_entry.get() password = password_entry.get() if username and password: conn = sqlite3.connect("todo_app.db") cursor = conn.cursor() cursor.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, password)) conn.commit() conn.close() messagebox.showinfo("Başarılı", "Kayıt başarılı! Giriş yapabilirsiniz.") else: messagebox.showerror("Hata", "Kullanıcı adı ve şifre boş olamaz!") root = tk.Tk() root.title("Giriş Yap") width, height = 200, 200 screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() x = (screen_width - width) // 2 y = (screen_height - height) // 2 root.geometry(f"{width}x{height}+{x}+{y}") # 设置窗口透明色(Windows平台有效,选背景图中不存在的颜色,这里用白色) root.attributes('-transparentcolor', '#ffffff') # 加载并调整背景图 background_image = Image.open("loginbackground.png") background_image = background_image.resize((width, height)) background_photo = ImageTk.PhotoImage(background_image) # 使用Canvas作为背景容器,直接在上面放置控件 background_canvas = tk.Canvas(root, width=width, height=height, highlightthickness=0) background_canvas.pack(fill="both", expand=True) background_canvas.create_image(0, 0, image=background_photo, anchor="nw") # 保存图片引用,防止被Python垃圾回收机制清理 background_canvas.background_photo = background_photo # 用户名标签 username_label = tk.Label(background_canvas, text="Kullanıcı Adı:", fg="black", bg="#ffffff") background_canvas.create_window(width//2, height//2 - 60, window=username_label) # 用户名输入框:移除边框,背景设为透明色 username_entry = tk.Entry(background_canvas, bd=0, relief="flat", highlightthickness=0, bg="#ffffff", fg="black") background_canvas.create_window(width//2, height//2 - 35, window=username_entry) # 密码标签 password_label = tk.Label(background_canvas, text="Şifre:", fg="black", bg="#ffffff") background_canvas.create_window(width//2, height//2 - 10, window=password_label) # 密码输入框 password_entry = tk.Entry(background_canvas, show="*", bd=0, relief="flat", highlightthickness=0, bg="#ffffff", fg="black") background_canvas.create_window(width//2, height//2 + 15, window=password_entry) # 登录按钮:移除边框,背景/点击背景设为透明色 login_btn = tk.Button(background_canvas, text="Giriş Yap", command=login, bd=0, relief="flat", bg="#ffffff", fg="black", activebackground="#ffffff") background_canvas.create_window(width//2, height//2 + 45, window=login_btn) # 注册按钮 register_btn = tk.Button(background_canvas, text="Kayıt Ol", command=register, bd=0, relief="flat", bg="#ffffff", fg="black", activebackground="#ffffff") background_canvas.create_window(width//2, height//2 + 75, window=register_btn) root.mainloop() def main_screen(user_id): def add_task(): task = task_entry.get() if task: conn = sqlite3.connect("todo_app.db") cursor = conn.cursor() cursor.execute("INSERT INTO tasks (user_id, task) VALUES (?, ?)", (user_id, task)) conn.commit() conn.close() task_entry.delete(0, tk.END) load_tasks() else: messagebox.showerror("Hata", "Görev boş olamaz!") def delete_task(task_id): conn = sqlite3.connect("todo_app.db") cursor = conn.cursor() cursor.execute("DELETE FROM tasks WHERE id = ?", (task_id,)) conn.commit() conn.close() load_tasks() def load_tasks(): for widget in task_frame.winfo_children(): widget.destroy() conn = sqlite3.connect("todo_app.db") cursor = conn.cursor() cursor.execute("SELECT id, task FROM tasks WHERE user_id = ?", (user_id,)) tasks = cursor.fetchall() conn.close() for task_id, task in tasks: frame = tk.Frame(task_frame) frame.pack(fill="x", pady=2) tk.Label(frame, text=task).pack(side="left", padx=5) tk.Button(frame, text="Sil", command=lambda tid=task_id: delete_task(tid)).pack(side="right") root = tk.Tk() root.title("Yapılacaklar Listesi") width, height = 800, 600 screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() x = (screen_width - width) // 2 y = (screen_height - height) // 2 root.geometry(f"{width}x{height}+{x}+{y}") task_entry = tk.Entry(root) task_entry.pack(pady=5) tk.Button(root, text="Ekle", command=add_task).pack(pady=5) task_frame = tk.Frame(root) task_frame.pack(pady=10) load_tasks() root.mainloop() # 启动程序 if __name__ == "__main__": setup_database() login_screen()
关键修改点说明
- 移除白色Frame:彻底删除了原代码中
bg='white'的login_frame,消除了白色背景遮挡。 - 使用Canvas承载背景:用Canvas绘制背景图,通过
create_window方法在Canvas上放置控件,确保控件直接显示在背景图上方。 - 透明色适配:通过
root.attributes('-transparentcolor', '#ffffff')将窗口的白色区域设为透明,同时把所有控件的bg设为白色,实现控件背景透明效果;按钮额外设置activebackground保证点击时仍保持透明。 - 修复窗口重叠问题:登录成功后调用
root.destroy()关闭登录窗口,避免同时存在两个窗口。
跨平台兼容提示
如果在Linux或Mac系统上-transparentcolor属性无效,可以将控件的bg设置为背景图对应位置的颜色(仅适合纯色背景),或者使用ttkbootstrap等第三方库实现原生透明控件。
内容的提问来源于stack exchange,提问作者Lark
相关产品推荐
相关产品推荐

