我在tkinter中嵌入了两个matplotlib图的画布小部件。我想使用fig1_canvas.get_tk_widget().configure(highlightthickness=3)
在这些框架周围绘制边框
fig2_canvas.get_tk_widget().configure(highlightthickness=3)
但这仅适用于两者之一。
我该如何解决?
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
root = tk.Tk()
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)
fig1_canvas.get_tk_widget().configure(highlightthickness=3)
ax2.plot(t, np.sin(t))
fig2.tight_layout()
fig2_canvas = FigureCanvasTkAgg(fig2, master=root)
fig2_canvas.get_tk_widget().configure(highlightthickness=3)
frame1 = tk.Frame()
frame2 = tk.Frame()
tk.Label(frame1, text='hello').pack()
tk.Label(frame2, text='world').pack()
frame1.grid(row=0, column=0, rowspan=2)
fig1_canvas.get_tk_widget().grid(row=0, column=1)
fig2_canvas.get_tk_widget().grid(row=1, column=1)
frame2.grid(row=2, column=0, columnspan=2)
tk.mainloop()
答案 0 :(得分:1)
如果您想在图形周围放置具有不同颜色的扁平边框,则可以将它们嵌入所需颜色的框架中,并使用padx
和pady
选项留出空白:
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
root = tk.Tk()
# frames to create the black border:
fig_frame1 = tk.Frame(root, background='black', padx=2, pady=2)
fig_frame2 = tk.Frame(root, background='black', padx=2, pady=2)
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=fig_frame1) # set master of fig1_canvas to the border frame
fig1_canvas.get_tk_widget().pack(padx=1, pady=1) # change padx and pady to choose the thickness of the border
ax2.plot(t, np.sin(t))
fig2.tight_layout()
fig2_canvas = FigureCanvasTkAgg(fig2, master=fig_frame2)
fig2_canvas.get_tk_widget().pack(padx=1, pady=1)
frame1 = tk.Frame()
frame2 = tk.Frame()
tk.Label(frame1, text='hello').pack()
tk.Label(frame2, text='world').pack()
frame1.grid(row=0, column=0, rowspan=2)
# put the border frames in the root window
fig_frame1.grid(row=0, column=1)
fig_frame2.grid(row=1, column=1)
frame2.grid(row=2, column=0, columnspan=2)