从儿童窗口获取条目?

时间:2014-12-07 05:57:04

标签: python tkinter turtle-graphics mainwindow toplevel

出于某种原因,我无法从子窗口获取条目。 我想从子窗口获取条目,然后绘制矩形图。 我得到的错误是:x = float(self.txtSide.get()) AttributeError:' MainWindow'对象没有属性' txtSide'

import tkinter as tk
import turtle
tu=turtle


class MainWindow(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.button = tk.Button(self, text="Cupe",command=self.Cupe)
        self.button.pack(side="top")

    def Cupe(self):

        c = tk.Toplevel(self)
        c.wm_title("Cupe")

        lab=tk.Label(c,text="Side")
        lab.pack()

        c.txtSide=tk.Entry(c)
        c.txtSide.pack()


        button=tk.Button(c,text="Graph",command=self.graphCupe)
        button.pack(side="bottom")


    def graphCupe(self):
        x=float(self.txtSide.get())
        tu.forward(x)
        tu.left(90)
        tu.forward(x)
        tu.left(90)
        tu.forward(x)
        tu.left(90)
        tu.forward(x)

if __name__ == "__main__":
    root = tk.Tk()
    main = MainWindow(root)
    main.pack(side="top", fill="both", expand=True)
    root.mainloop()

1 个答案:

答案 0 :(得分:1)

问题是self中的graphCupe是指MainWindow个实例,而不是子窗口。您需要将子窗口传递到graphCupe函数。这是一种方法:

    def Cupe(self):
        ...
        button=tk.Button(c,text="Graph",command=lambda: self.graphCupe(c))
        button.pack(side="bottom")

    def graphCupe(self,window):
        x=float(window.txtSide.get())
        ...

现在graphCupe函数接受了操作所需的窗口,按钮调用该函数并将其传递给子窗口。