TEST_PLOT.py
[![import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
class TestPlot:
def __init__(self, master=None):
self.master = master
self.create_plot()
def create_plot(self):
# Generate x values
x = np.linspace(-10, 10, 400)
# Compute y values
y = x**2
# Create the plot
self.fig, self.ax = plt.subplots(figsize=(8, 6))
self.ax.plot(x, y, label='$y = x^2$')
self.ax.set_title('Plot of $y = x^2$')
self.ax.set_xlabel('x')
self.ax.set_ylabel('y')
self.ax.legend()
self.ax.grid(True)
if self.master:
# Embed the plot in the Tkinter frame
self.canvas = FigureCanvasTkAgg(self.fig, master=self.master)
self.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
self.canvas.draw()
else:
# Show the plot standalone
plt.show()
if __name__ == "__main__":
一切都漂亮又锋利。
但是当我在框架中使用这个脚本时,它变得有点模糊:
test1.py
import tkinter as tk
from TEST_PLOT import TestPlot # Assuming the above code is saved in test_plot.py
class Test1(tk.Tk):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.title('Test1 - Main Window with Plot')
self.geometry('800x600')
# Create a single frame for the plot
frame = tk.Frame(self, bg='lightblue', bd=5, relief=tk.RIDGE)
frame.pack(fill=tk.BOTH, expand=True)
# Embed TestPlot within the frame
test_plot = TestPlot(frame)
test_plot.master.pack(fill=tk.BOTH, expand=True)
if __name__ == '__main__':
app = Test1()
app.mainloop()
当然这是一些压缩问题,但不确定解决问题的最佳方法是什么。
希望使用 Tkinter 作为 Python 的默认设置。尽管我愿意接受更好的图形选项。
当我在实际程序中使用它时,还会发生一些非常奇怪的事情,Tkinter 图标本身变得模糊..