1

嘿,伙计们第一次发帖,什么不是那么嗨。无论如何,试图用 tkinter 制作一个科学计算器,但我对它不是很好(而 python 是我的第二个正确任务)。无论如何,大多数代码都可能是错误的,但我只是想一步一步地采取它,特别是我关心函数添加。我通过按钮调用它但是我想传递do函数a +。这反过来创建了一个我可以计算的数组。它不断出错,我不知道如何解决它。现在真的很烦我,所以如果有人能帮忙,将不胜感激

from tkinter import*
from operator import*

class App:
    def __init__(self,master):#is the master for the button widgets
        frame=Frame(master)
        frame.pack()
        self.addition = Button(frame, text="+", command=self.add)#when clicked sends a call back for a +
        self.addition.pack()
    def add(Y):
        do("+")
    def do(X):#will hopefully colaborate all of the inputs
        cont, i = True, 0
        store=["+","1","+","2","3","4"]
        for i in range(5):
            X=store[0+i]
            print(store[0+i])
            cont = False
        if cont == False:
            print(eval_binary_expr(*(store[:].split())))
    def get_operator_fn(op):#allows the array to be split to find the operators
        return {
            '+' : add,
            '-' : sub,
            '*' : mul,
            '/' : truediv,
            }[op]
    def eval_binary_expr(op1, num1, op2, num2):
        store[1],store[3] = int(num1), int(num2)
        return get_operator_fn(op2)(num1, num2)


root=Tk()
app=App(root)
root.mainloop()#runs programme
4

1 回答 1

2

Generally speaking, every method in a class should take self as its first argument. The name self is just a convention. It is not a keyword in Python. However, when you call a method such as obj.add(...), the first argument sent to the method is the instance obj. It is a convention to call that instance self in the method definition. So all your methods need to be modified to include self as the first argument:

class App:
    def __init__(self, master):#is the master for the button widgets
        frame=Frame(master)
        frame.pack()
        self.addition = Button(frame, text="+", command=self.add)#when clicked sends a call back for a +
        self.addition.pack()
    def add(self):
        self.do("+")
    def do(self, X):
        ...

Note that when you call self.do("+"), inside the method do, X will be bound to "+". Later on in that method I see

X=store[0+i]

which will rebind X to the value store[i]. I don't know what you are trying to do here, but be aware that doing so means you've just lost the "+" value that was just passed in.

于 2013-08-20T01:09:50.753 回答