如何在Tkinter中禁用按钮按下效果
Hey there! I totally get how frustrating that tiny press offset and white border can be when you're trying to build a clean, polished GUI. Let's walk through two solid solutions to disable that default button press effect for good.
Option 1: Tweak the Standard Tkinter Button
Your current code is already halfway there—you just need to add a couple more parameters to lock the button's appearance across all states:
from tkinter import * window = Tk() window.geometry("900x500") window.configure(bg = "#00B2FF") Submit_icon = PhotoImage(file = r"picture.jpg") Submit_Button = Button(window, image = Submit_icon, bd = 0, borderwidth=0, highlightthickness = 0, highlightcolor= "#00B2FF", relief = "flat", activeforeground="#00B2FF", activebackground="#00B2FF", # Match window background when pressed activeimage=Submit_icon, # Use the same image for pressed state overrelief="flat" # No border change on mouse hover ) Submit_Button.pack(pady=10) window.mainloop()
Key Changes Explained:
activebackground="#00B2FF": Makes the button's background identical to your window when pressed, so no visible border or color shift appears.activeimage=Submit_icon: Forces the button to display the exact same image in its pressed state (instead of the default shifted version that causes the offset).overrelief="flat": Optional but recommended—prevents any border changes when the mouse hovers over the button for a fully consistent look.
Option 2: Use ttk.Button with a Custom Style
For even more control over your button's appearance (and to avoid any default theme quirks), use ttk.Button with a fully customized style:
from tkinter import * from tkinter import ttk window = Tk() window.geometry("900x500") window.configure(bg = "#00B2FF") # Customize the ttk style to eliminate all press effects style = ttk.Style() style.theme_use('clam') # Start with a theme that's easy to modify style.configure('NoPress.TButton', background="#00B2FF", borderwidth=0, relief="flat", padding=0) # Remove internal padding to stop press offset # Map all button states to match the normal appearance style.map('NoPress.TButton', background=[('active', '#00B2FF'), ('pressed', '#00B2FF')], relief=[('active', 'flat'), ('pressed', 'flat')], borderwidth=[('active', 0), ('pressed', 0)]) Submit_icon = PhotoImage(file = r"picture.jpg") Submit_Button = ttk.Button(window, image = Submit_icon, style='NoPress.TButton') Submit_Button.pack(pady=10) window.mainloop()
Why This Works:
Using style.map() lets us explicitly set the active (hover) and pressed states to mirror the button's normal appearance. Setting padding=0 also ensures there's no internal shift when the button is pressed, completely eliminating the default press effect.
Either of these methods should get rid of that annoying offset and white border you're dealing with!
内容的提问来源于stack exchange,提问作者Martin Šafrata

