如何实现GUI类与逻辑类的交互

1 投票
1 回答
1673 浏览
提问于 2025-04-15 22:37

我刚开始学习图形用户界面(GUI)编程,对面向对象编程(OOP)也不太熟悉。我正在做一个简单的计算器应用程序,目的是帮助我学习GUI设计,同时复习一下OOP。我知道GUI相关的内容应该和逻辑部分分开,但我不太确定如何在需要的时候让逻辑和GUI之间进行互动,比如说,如何把变量来回传递……

我在使用TKinter,当我把一个tkinter变量传给我的逻辑部分时,它似乎只保存了字符串PY_VAR0。

def on_equal_btn_click(self):
            self.entryVariable.set(self.entryVariable.get() + "=")
            calculator = Calc(self.entryVariable)
            self.entryVariable.set(calculator.calculate())

我觉得我可能在某些基本的地方做错了,可能还挺傻的。我花了不少时间在实验(和网上找答案),但一直没有进展。任何帮助都会很感激。

谢谢,
V

完整程序(其实只是展示结构的部分……)

import Tkinter

class Gui(Tkinter.Tk):
    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.grid()
        self.create_widgets()
        """ grid config """
        #self.grid_columnconfigure(0,weight=1,pad=0)
        self.resizable(False, False)

    def create_widgets(self):

        """row 0 of grid"""

        """Create Text Entry Box"""
        self.entryVariable = Tkinter.StringVar()
        self.entry = Tkinter.Entry(self,width=30,textvariable=self.entryVariable)
        self.entry.grid(column=0,row=0, columnspan = 3 )
        self.entry.bind("<Return>", self.on_press_enter)

        """create equal button"""
        equal_btn = Tkinter.Button(self,text="=",width=4,command=self.on_equal_btn_click)
        equal_btn.grid(column=3, row=0)

        """row 1 of grid"""

        """create number 1 button"""
        number1_btn = Tkinter.Button(self,text="1",width=8,command=self.on_number1_btn_click)
        number1_btn.grid(column=0, row=1)

    def on_equal_btn_click(self):
        self.entryVariable.set(self.entryVariable.get() + "=")
        calculator = Calc(self.entryVariable.get())
        self.entryVariable.set(calculator.calculate())

class Calc():

    def __init__(self, equation):
        self.equation = equation

    def calculate(self):
        #TODO: parse string and calculate...
        return self.equation 

# define undefined functions for sufficiently liberal meanings of "define"
Gui.on_press_enter = Gui.on_equal_btn_click
Gui.on_number1_button_click = Gui.on_equal_btn_click

if __name__ == "__main__":
    app = Gui(None)
    app.title('Calculator')
    app.mainloop()   

1 个回答

2

更正:

我之前的回答完全错误,请忽略它。问题在于你不小心把你的变量文本覆盖成了entryVariable对象的字符串表示。注意在调用Calc()时加上了get()

def on_equal_btn_click(self):
    print self.entryVariable.get()
    self.entryVariable.set(self.entryVariable.get() + "=")
    print self.entryVariable.get()
    calculator = Calc(self.entryVariable.get())
    self.entryVariable.set(calculator.calculate())

欢迎来到弱类型语言的世界,这种错误可能会让你抓狂。在这种情况下,我发现多用printrepr()(或者print('foo %r' % object))非常有帮助。

撰写回答