0

我目前正在尝试用 python 制作一个计算器,我首先为它创建了一个简单的 GUI。但是,在使按钮工作时,我在尝试输出数字时不断收到类型错误。我该如何解决这个问题?在执行所需的所有其他命令之前,我已经开始尝试输出 0 来测试运行。

import tkinter as t

window = None
display_label = None
expression = ''


def setup_GUI():


    global window
    global dsiplay_label

    window = t.Tk()
    window.title("calculator")


    display_label = t.Label(window, textvariable='', anchor='e', relief=t.GROOVE, width=15, font='Arial 20')
    display_label.grid(row=0, column=0, columnspan=4, padx=10, pady=10)


    #numbers

    btn1 = t.Button(window, text='1', width=5, height=2, font='Arial 15',command = press0)
    btn2 = t.Button(window, text='2', width=5, height=2, font='Arial 15')
    btn3 = t.Button(window, text='3', width=5, height=2, font='Arial 15')
    btn4 = t.Button(window, text='4', width=5, height=2, font='Arial 15')
    btn5 = t.Button(window, text='5', width=5, height=2, font='Arial 15')
    btn6 = t.Button(window, text='6', width=5, height=2, font='Arial 15')
    btn7 = t.Button(window, text='7', width=5, height=2, font='Arial 15')
    btn8 = t.Button(window, text='8', width=5, height=2, font='Arial 15')
    btn9 = t.Button(window, text='9', width=5, height=2, font='Arial 15')
    btn0 = t.Button(window, text='0', width=5, height=2, font='Arial 15')

    #operators

    clear = t.Button(window, text = "C", width=5, height=2, font='Arial 15')
    percent = t.Button(window, text = "%", width=5, height=2, font='Arial 15')
    squared = t.Button(window, text = "X²", width=5, height=2, font='Arial 15')
    ineq = t.Button(window, text = "<", width=5, height=2, font='Arial 15')
    period = t.Button(window, text = "ㆍ", width=5, height=2, font='Arial 15')
    mul = t.Button(window, text = "×", width=5, height=2, font='Arial 15')
    div = t.Button(window, text = "÷", width=5, height=2, font='Arial 15')
    add = t.Button(window, text = "+", width=5, height=2, font='Arial 15')
    sub = t.Button(window, text = "-", width=5, height=2, font='Arial 15')
    result = t.Button(window, text = "=", width=5, height=2, font='Arial 15')


    #positions

    btn1.grid(row=2, column=0)
    btn2.grid(row=2, column=1)
    btn3.grid(row=2, column=2)
    btn4.grid(row=3, column=0)
    btn5.grid(row=3, column=1)
    btn6.grid(row=3, column=2)
    btn7.grid(row=4, column=0)
    btn8.grid(row=4, column=1)
    btn9.grid(row=4, column=2)
    btn0.grid(row=5, column=1)
    clear.grid(row=1, column=0)
    result.grid(row=5, column=2)
    add.grid(row=2, column=3)
    sub.grid(row=3, column=3)
    mul.grid(row=4, column=3)
    div.grid(row=5, column=3)
    period.grid(row=5, column=0)
    ineq.grid(row=1, column=1)
    percent.grid(row=1,column=2)
    squared.grid(row=1,column=3)




def press0():
    global expression
    expression = expression + '0'
    display_label['text']= expression


setup_GUI()
window.mainloop()
4

2 回答 2

0

你拼错display_labelglobal dsiplay_label

于 2020-11-21T13:01:14.943 回答
0

在 GUI 函数中定义全局变量display_label时,您拼错了它。

于 2020-11-21T12:50:23.963 回答