tkinter按钮按下以进行功能调用

时间:2013-08-20 00:53:54

标签: python python-3.x tkinter

嘿伙计们先发帖,什么不那么喜欢。无论如何试图用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

1 个答案:

答案 0 :(得分:2)

一般来说,类中的每个方法都应该以{{1​​}}作为第一个参数。名称self只是一个惯例。它不是Python中的关键字。但是,当您调用self之类的方法时,发送给该方法的第一个参数是实例obj.add(...)。在方法定义中调用该实例obj是一种惯例。因此,需要修改所有方法以包含self作为第一个参数:

self

请注意,当您致电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): ... 时,在方法self.do("+")内,do将绑定到X。后来在那种方法中我看到了

"+"

会将X=store[0+i] 重新绑定到值X。我不知道你在这里要做什么,但要注意这样做意味着你刚刚丢失了传入的store[i]值。