【问题标题】:Calling functions from classes with inheritence从具有继承的类中调用函数
【发布时间】:2020-05-31 17:36:37
【问题描述】:

我确定我在类/继承理解方面遗漏了一些东西。 当我点击提交按钮时,我收到此错误:

我尝试了许多变化,例如更改按钮中的命令、更改主控、定义 self.controller。

如何使提交按钮起作用?

import tkinter as tk
import os

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.geometry("650x500")
        self.title("Gil Shwartz GUI Project")
        menu = tk.Frame(self, height=250, width=10, bg="black")
        menu.pack(side=tk.LEFT, fill="both", anchor="w")
        container = tk.Frame(self, height=250, width=270, relief="flat")
        container.pack(side=tk.TOP, fill="both", expand=True)
        output = tk.LabelFrame(self, text="Output", height=150, padx=5, pady=5)
        output.pack(side=tk.BOTTOM, fill="both", anchor="s")

        menu.grid_columnconfigure(0, weight=0)
        menu.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(1, weight=1)

        self.frames = ["StartPage", "MainWelcome", "testPing", "PageOne", "PageTwo"]

        self.frames[0] = Menu(parent=menu, controller=self)
        self.frames[1] = MainWelcome(parent=container, controller=self)
        self.frames[2] = testPing(parent=container, controller=self)
        self.frames[3] = PageOne(parent=container, controller=self)
        self.frames[4] = PageTwo(parent=container, controller=self)

        self.frames[0].grid(row=0, column=0, sticky="nsew")
        self.frames[1].grid(row=0, column=0, sticky="nsew")
        self.frames[2].grid(row=0, column=0, sticky="nsew")
        self.frames[3].grid(row=0, column=0, sticky="nsew")
        self.frames[4].grid(row=0, column=0, sticky="nsew")

        self.show_frame(1)

    def show_frame(self, page_name):
        frame = self.frames[page_name]
        print(frame)
        frame.tkraise()

class Menu(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.menu = controller

        button1 = tk.Button(self, text="Ping Test",
                            command=lambda: controller.show_frame(2))
        button2 = tk.Button(self, text="Page Two",
                            command=lambda: controller.show_frame(4))
        button3 = tk.Button(self, text="Quit",
                            command=lambda: Menu.terminate(self))

        button1.pack(fill="both", expand=True)
        button2.pack(fill="both", expand=True)
        button3.pack(fill="both", expand=True)
        button1.grid_columnconfigure(0, weight=1)
        button2.grid_columnconfigure(0, weight=0)
        button3.grid_rowconfigure(0, weight=0)

    def terminate(self):
        exit()

class MainWelcome(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.menu = controller

        label = tk.Label(self, text="Text 1", bg="yellow")
        label.pack(fill="x", expand=True)
        label = tk.Label(self, text="Text 2", bg="yellow")
        label.pack(fill="x")


class testPing(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.urlLabel = controller

        urlLabel = tk.Label(self, text="Enter URL : ", padx=5, pady=5)
        urlLabel.pack(anchor="w")
        urlInputBox = tk.Entry(self)
        urlInputBox.pack()
        urlInputBox.grid_columnconfigure(0, weight=0)

        clearLabel = tk.Label(self, text="Clear File?", padx=5, pady=5)
        clearLabel.pack(anchor="w")

        clearFile = tk.BooleanVar()
        clearFile.set(False)
        clearFileRadioYes = tk.Radiobutton(self, text="yes", value=True, var=clearFile,
                                           command=lambda: testPing.callback(clearFile.get()))
        clearFileRadioYes.pack(anchor="w")
        clearFileRadioNo = tk.Radiobutton(self, text="no", value=False, var=clearFile,
                                          command=lambda: testPing.callback((clearFile.get())))
        clearFileRadioNo.pack(anchor="w")

        urlSubmitButton = tk.Button(self, text="Submit",
                                    command=lambda: testPing.pingURL(urlInputBox.get(),
                                                     testPing(clearFile.get())))
        urlSubmitButton.pack(side=tk.RIGHT, anchor="e")

    def callback(clearFile):
        print(clearFile) # Debugging Mode - check Radio box Var.

    def pingURL(self, host, clearFile):

        outputFrameLabel = tk.LabelFrame(self, text="Output", height=35, width=150,
                               padx=5, pady=5, relief="solid")
        outputFrameLabel.place(x=0, y=150)
        file = fr'c:/users/{os.getlogin()}/Desktop/ping.txt'
        label = tk.Label(outputLabel, text=f'Pinging {host} ...')
        label.grid(row=0, column=0)
        label.update()

        if clearFile == True:
            with open(file, 'w+') as output:
                output.truncate(0)
                sub.call(['ping', f'{host}'], stdout=output)

        else:
            with open(file, 'a') as output:
                sub.call(['ping', f'{host}'], stdout=output)

        output.close()
        label.configure(text=f'Ping to {host} complete!')
        # testPing.changeLabel(host)

    # def changeLabel(self, host):

        # myLabel = tk.Label.config(text=f"Ping to {host} Complete!")
        # myLabel.pack()


class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", bg="red")
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to page 2",
                           command=lambda: controller.show_frame(2))
        button.pack()


class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 2", bg="blue")
        label.pack(side="top", fill="x", pady=10)
        # button = tk.Button(self, text="Go to the start page",
        #                    command=lambda: controller.show_frame(0))
        # button.pack()


if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

这是主窗口的图片,因此您也将获得一个直观的想法。

【问题讨论】:

  • 错误是什么?
  • 哎呀,哈哈,刚刚添加了它!接得好! :)
  • 当您编写代码行testPing(clearFile.get())时,您缺少所需的变量controller,因为您只传递了变量parent

标签: python class inheritance tkinter


【解决方案1】:

我认为错误在于testPing 类;特别是在这些方面:

class testPing(tk.Frame):
...
        clearFileRadioYes = tk.Radiobutton(self, text="yes", value=True, var=clearFile,
                                           command=lambda: testPing.callback(clearFile.get()))
        clearFileRadioYes.pack(anchor="w")
        clearFileRadioNo = tk.Radiobutton(self, text="no", value=False, var=clearFile,
                                          command=lambda: testPing.callback((clearFile.get())))
        clearFileRadioNo.pack(anchor="w")

        urlSubmitButton = tk.Button(self, text="Submit",
                                    command=lambda: testPing.pingURL(urlInputBox.get(),
                                                     testPing(clearFile.get())))

您在testPing 内部,因此您应该使用self 而不是明确使用testPing。所以,你的代码应该是:

class testPing(tk.Frame):
...
        clearFileRadioYes = tk.Radiobutton(self, text="yes", value=True, var=clearFile,
                                           command=lambda: self.callback(clearFile.get()))
        clearFileRadioYes.pack(anchor="w")
        clearFileRadioNo = tk.Radiobutton(self, text="no", value=False, var=clearFile,
                                          command=lambda: self.callback((clearFile.get())))
        clearFileRadioNo.pack(anchor="w")

        urlSubmitButton = tk.Button(self, text="Submit",
                                    command=lambda: self.pingURL(urlInputBox.get(),
                                                     clearFile.get()))

注意使用self 而不是testPing

【讨论】:

  • 它的工作原理!我不得不更多地调整代码以适应它,但它确实完成了工作!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-27
  • 2017-03-11
  • 1970-01-01
  • 2014-10-31
  • 2016-03-01
相关资源
最近更新 更多