Tkinter嵌入Matplotlib画布边框仅一个生效的解决方法
Hey there, the issue here comes down to misunderstanding what Tkinter's highlightthickness property actually does—it's a focus highlight border, meaning it only appears when the widget has keyboard focus. That's why only one of your canvases shows it at a time (whichever one is currently focused).
If you want a persistent border around both canvases (which I assume is what you're going for), you need to use Tkinter's borderwidth and relief properties instead. You can still keep highlightthickness if you want the focus highlight as an extra, but the persistent border will come from the other two properties.
Updated Code
import tkinter as tk import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import numpy as np root = tk.Tk() # Create figures and plots fig1, ax1 = plt.subplots(figsize=(2, 2)) fig2, ax2 = plt.subplots(figsize=(2, 2)) t = np.arange(0, 2*np.pi, 0.1) ax1.plot(t, np.cos(t)) fig1.tight_layout() fig1_canvas = FigureCanvasTkAgg(fig1, master=root) # Configure persistent border + optional focus highlight fig1_canvas.get_tk_widget().configure( borderwidth=3, relief="solid", highlightthickness=3 # Keeps focus highlight if needed ) ax2.plot(t, np.sin(t)) fig2.tight_layout() fig2_canvas = FigureCanvasTkAgg(fig2, master=root) fig2_canvas.get_tk_widget().configure( borderwidth=3, relief="solid", highlightthickness=3 ) # Set up frames and labels frame1 = tk.Frame() frame2 = tk.Frame() tk.Label(frame1, text='hello').pack() tk.Label(frame2, text='world').pack() # Layout with padding to avoid border overlap frame1.grid(row=0, column=0, rowspan=2) fig1_canvas.get_tk_widget().grid(row=0, column=1, padx=5, pady=5) fig2_canvas.get_tk_widget().grid(row=1, column=1, padx=5, pady=5) frame2.grid(row=2, column=0, columnspan=2) tk.mainloop()
Key Details
borderwidth: Sets the width of a permanent border that's always visible on the widget.relief: Defines the style of the border—"solid"gives you a plain line, but you can also use"raised","sunken","groove", or"ridge"for different visual effects.highlightthickness: If you still want a visual indicator when the canvas has focus, keep this property. It will add an extra highlight around the widget when it's selected (e.g., via pressing the Tab key to switch focus).
I also added padx and pady to the grid calls to give some space between the borders and other widgets, making the overall layout look cleaner and less cramped.
内容的提问来源于stack exchange,提问作者Bruno Vermeulen

