Tkinter gui计算器

时间:2014-09-11 12:34:36

标签: python tkinter calculator

嘿,我想在按下按钮时在计算器上这样做,在屏幕上输入点击按钮的数字。有人会想到以最有效的方式做到这一点吗? 到目前为止,这是我的代码。

import tkinter

window = tkinter.Tk()
window.geometry("150x170")

lbl1 = tkinter.Label(text = "Calculator").grid(row = 1, column = 4)

displaynum = 0
lb = tkinter.Label(text = displaynum, borderwidth = 4).grid(row = 2, column = 4)
def displayednum():
    global displaynum
    lbl = tkinter.Label(text = displaynum, borderwidth = 4).grid(row = 2, column = 4)

for n in range(1,4):
    btn1 = tkinter.Button(text = n,borderwidth = 2, command = changenumber ).grid(row = 3,column = n*2)
    lbl2 = tkinter.Label(text = " ").grid(row = 3, column = n*2+1)
for u in range(1,4):
    btn2 = tkinter.Button(text = u+3,borderwidth = 2).grid(row = 6, column = u*2)
    lbl3 = tkinter.Label(text = " ").grid(row = 6, column = u*2+1)
for m in range(1,4):
    btn2 = tkinter.Button(text = m+6,borderwidth = 2).grid(row = 9, column = m*2)
    lbl4 = tkinter.Label(text = " ").grid(row = 9, column = m*2+1)


window.mainloop()

有人有解决方案吗?

1 个答案:

答案 0 :(得分:0)

更改标签文本的功能可以这样实现:

def changenumber(label, val):
    label.config(text=str(val))

但是在分配变量时应该小心。 变量lbl1和lb都是None。 你应该这样试试:

lbl1 = tkinter.Label(text = "Calculator")
lbl1.grid(row = 1, column = 4)
lb = tkinter.Label(text = displaynum, borderwidth = 4)
lb.grid(row = 2, column = 4)