你好我试图从python中的另一个类执行一个函数。我试过在同一个类中完成所有这一切,现在我在不同的类中尝试这个。这里的目标是在按钮下方的tkinter窗口中显示图形。我编写了一个生成图形的函数,我试图让它在加载GUI组件后执行图形函数。稍后我会将参数传递给它,因此它需要成为一个函数。我得到的错误是AttributeError:'graphPlotter'对象没有属性'tk。有没有人知道这方面的工作或者更聪明的方法呢?请参阅以下代码:
import sys
from tkinter import *
import matplotlib
matplotlib.use("TKAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
class graphPlotter:
def graphdis(self):
# ***** Component graph Display *****
f=Figure(figsize=(5,5), dpi=100)
a=f.add_subplot(111)
a.plot([1,2,3,4,5,6],[1,2,3,4,5,6])
canvas = FigureCanvasTkAgg(f,self)
canvas.show()
canvas.get_tk_widget().pack()
class GUIWindow:
root = Tk()
root.geometry('1200x650')
# ****** GUI buttons *********
radomeButton = Button(root, text="Radome", bd="4")
wingsButton = Button(root, text="Wings", bd="4")
engineButton = Button(root, text="Engine", bd="4")
finsButton = Button(root, text="Fins", bd="4")
fuelButton = Button(root, text="Fuel", bd="4")
radomeButton.place(x=25,y=25)
wingsButton.place(x=175,y=25)
engineButton.place(x=235,y=25)
finsButton.place(x=300,y=25)
fuelButton.place(x=356,y=25)
graphGrab = graphPlotter()
graphGrab.graphdis()
root.mainloop()
我对python比较陌生,所以我确定我错过了什么。
感谢。
答案 0 :(得分:0)
Canvas需要正确的父级 - root
现在它可以正常运行,但它并不好看,因为你混合了place
和pack
布局管理器。
import sys
from tkinter import *
import matplotlib
matplotlib.use("TKAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
class GraphPlotter:
def __init__(self, parent):
# remember parent
self.parent = parent
def graphdis(self):
f = Figure(figsize=(5,5), dpi=100)
a = f.add_subplot(111)
a.plot([1,2,3,4,5,6],[1,2,3,4,5,6])
# canvas need correct parent - root
canvas = FigureCanvasTkAgg(f, self.parent)
canvas.show()
canvas.get_tk_widget().pack()
class GUIWindow:
def __init__(self):
root = Tk()
root.geometry('1200x650')
# ****** GUI buttons *********
radomeButton = Button(root, text="Radome", bd="4")
wingsButton = Button(root, text="Wings", bd="4")
engineButton = Button(root, text="Engine", bd="4")
finsButton = Button(root, text="Fins", bd="4")
fuelButton = Button(root, text="Fuel", bd="4")
radomeButton.place(x=25, y=25)
wingsButton.place(x=175, y=25)
engineButton.place(x=235, y=25)
finsButton.place(x=300, y=25)
fuelButton.place(x=356, y=25)
# use `root` as parent for canvas
graphGrab = GraphPlotter(root)
graphGrab.graphdis()
root.mainloop()
GUIWindow()