天天看点

python中label函数_python – 如何修改/添加文本到tkinter.Label?

我正在学习基本的

Python.我目前正在尝试创建一个只有加法和减法的简单计算器程序.我有一个问题.我不确定如何在按下按钮时将文本添加到我的Python标签中.现在,按下“1”按钮后,我的程序会将显示标签更改为文本“1”.但是,我希望我的程序添加文本,而不是设置它.

例如,如果我按下“按钮1”5次,它当前将重置标签文本5次,并将产生单个1.我希望它在按下时将数字添加到标签,而不是替换.

按下按钮5次后的当前结果:1

按下按钮5次后请求的结果:11111

这是我目前的程序代码.如果有什么不清楚,请问;谢谢.

from tkinter import *

window = Tk()

# Creating main label

display = Label(window, text="")

display.grid(row=0, columnspan=3)

def add_one():

display.config(text='1')

# Creating all number buttons

one = Button(window, text="1", height=10, width=10, command=add_one)

two = Button(window, text="2", height=10, width=10)

three = Button(window, text="3", height=10, width=10)

four = Button(window, text="4", height=10, width=10)

five = Button(window, text="5", height=10, width=10)

six = Button(window, text="6", height=10, width=10)

seven = Button(window, text="7", height=10, width=10)

eight = Button(window, text="8", height=10, width=10)

nine = Button(window, text="9", height=10, width=10)

zero = Button(window, text="0", height=10, width=10)

# Placing all number buttons

one.grid(row=1, column=0)

two.grid(row=1, column=1)

three.grid(row=1, column=2)

four.grid(row=2, column=0)

five.grid(row=2, column=1)

six.grid(row=2, column=2)

seven.grid(row=3, column=0)

eight.grid(row=3, column=1)

nine.grid(row=3, column=2)

# Creating all other buttons

add = Button(window, text="+", height=10, width=10)

subtract = Button(window, text="-", height=10, width=10)

equal = Button(window, text="=", height=10, width=10)

# Placing all other buttons

add.grid(row=4, column=0)

subtract.grid(row=4, column=1)

equal.grid(row=4, column=2)

window.mainloop()