首页 > 解决方案 > 如何正确地将我在计算器中按下的数字插入到最后一个索引处的文本小部件中?

问题描述

例如,当我按下“100”时,它会在文本框中输出“001”。我尝试在索引中使用 -1 但同样的事情仍然发生,我也尝试执行 .insert(0. end, num) 但它会引发错误。如何让数字始终在输出末尾输入。另外,这是用 tkinter 输出数字的最佳方法还是有其他方法(如果有)?

from tkinter import *
import operator

window = Tk()
window.title('Calculator')

def click(num):
    output.insert(0.0, num) #numbers not properly inputted (bug)

#output for calculator
output = Text(window, font = 'none 12 bold', height = 4, width = 25, wrap = 'word')
output.grid(row = 0, column = 0, columnspan = 4, pady = 10)

###buttons
#clear and operators
b_clear = Button(window, text = 'C', width = 7, height = 3)
b_clear.grid(row = 1, column = 2, padx = (10, 0))

b_div = Button(window, text = '/', width = 7, height = 3)
b_div.grid(row = 1, column = 3, padx = 10)

b_mult = Button(window, text = '*', width = 7, height = 3)
b_mult.grid(row = 2, column = 3)

b_subt = Button(window, text = '-', width = 7, height = 3)
b_subt.grid(row = 3, column = 3)

b_add = Button(window, text = '+', width = 7, height = 3)
b_add.grid(row = 4, column = 3)

b_equal = Button(window, text = '=', width = 7, height = 3)
b_equal.grid(row = 5, column = 3, pady = (0, 10))

#numbers
b_9 = Button(window, text = '9', width = 7, height = 3, command = lambda: click(9))
b_9.grid(row = 2, column = 2, padx = (10, 0), pady = 10)

b_8 = Button(window, text = '8', width = 7, height = 3, command = lambda: click(8))
b_8.grid(row = 2, column = 1)

b_7 = Button(window, text = '7', width = 7, height = 3, command = lambda: click(7))
b_7.grid(row = 2, column = 0, padx = 10)

b_6 = Button(window, text = '6', width = 7, height = 3, command = lambda: click(6))
b_6.grid(row = 3, column = 2, padx = (10, 0))

b_5 = Button(window, text = '5', width = 7, height = 3, command = lambda: click(5))
b_5.grid(row = 3, column = 1)

b_4 = Button(window, text = '4', width = 7, height = 3, command = lambda: click(4))
b_4.grid(row = 3, column = 0)

b_3 = Button(window, text = '3', width = 7, height = 3, command = lambda: click(3))
b_3.grid(row = 4, column = 2, padx = (10, 0), pady = 10)

b_2 = Button(window, text = '2', width = 7, height = 3, command = lambda: click(2))
b_2.grid(row = 4, column = 1)

b_1 = Button(window, text = '1', width = 7, height = 3, command = lambda: click(1))
b_1.grid(row = 4, column = 0)

b_0 = Button(window, text = '0', width = 7, height = 3, command = lambda: click(0))
b_0.grid(row = 5, column = 0, pady = (0, 10))

b_decimal = Button(window, text = '.', width = 7, height = 3)
b_decimal.grid(row = 5, column = 1, pady = (0, 10))

b_negative = Button(window, text = '-', width = 7, height = 3)
b_negative.grid(row = 5, column = 2, padx = (10, 0), pady = (0, 10))

#run calculator
window.mainloop()

标签: pythontkinteroptimizationcalculator

解决方案


索引“end”表示小部件中最后一个字符之后的位置。

output.insert("end", num) 

来自官方文档:

end - 表示条目字符串中最后一个字符之后的字符。这等效于指定一个等于条目字符串长度的数字索引。


推荐阅读