【问题标题】:tkinter button press to function calltkinter 按钮按下以调用函数
【发布时间】:2013-08-21 22:20:01
【问题描述】:

嘿,伙计们第一次发帖,什么不是那么嗨。无论如何,试图用 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

【问题讨论】:

    标签: python python-3.x tkinter


    【解决方案1】:

    一般来说,类中的每个方法都应该将self 作为其第一个参数。 self 这个名字只是一个约定。它不是 Python 中的关键字。但是,当您调用诸如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("+") 时,在方法@​​987654329@ 内部,X 将绑定到"+"。后来在那个方法中我看到了

    X=store[0+i]
    

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

    【讨论】:

    • 我试图将“+”按顺序添加到数组中,这样当我有其他按钮时,我可以输入整个等式,而不必为每个数字按 Enter。正如我所说,虽然我仍然刚刚开始,所以它可能是非常低效的代码(并且或不工作),但只是那个顶部有助于卡车负载我无法弄清楚它为什么不能工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 2011-01-18
    • 2013-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多