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

例如,当我按下“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))


人到中年有点甜
浏览 106回答 2
2回答

慕哥9229398

索引“end”表示小部件中最后一个字符之后的位置。output.insert("end", num)来自官方文档:end - 表示条目字符串中最后一个字符之后的字符。这相当于指定一个等于条目字符串长度的数字索引。

子衿沉夜

你工作太辛苦了。从图形的角度来看,您必须考虑到您的按钮都是完全相同的东西。您只需几行就可以构建整个界面。由于每个按钮都会调用calc,只需编写条件语句来calc处理各种可能性。您可以在该函数中构建计算器的全部功能。import tkinter as tk&nbsp;window = tk.Tk()window.title('Calculator')#output for calculatoroutput = tk.Text(window, font = 'none 12 bold', height=4, width=25, wrap='word')output.grid(row=0, column=0, columnspan=4, pady=10)def calc(data):&nbsp; &nbsp; if data.isnumeric() or data == '.':&nbsp; &nbsp; &nbsp; &nbsp; output.insert('end', data)&nbsp; &nbsp; elif data in ['-', '+', '*', '/']:&nbsp; &nbsp; &nbsp; &nbsp; #write code for handling operators&nbsp; &nbsp; &nbsp; &nbsp; pass #delete this line&nbsp; &nbsp; elif data == '=':&nbsp; &nbsp; &nbsp; &nbsp; #write code for handling equals&nbsp; &nbsp; &nbsp; &nbsp; pass #delete this line&nbsp; &nbsp; elif data == 'pos':&nbsp; &nbsp; &nbsp; &nbsp; if output.get('1.0', '1.1') == '-':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output.delete('1.0', '1.1')&nbsp;&nbsp; &nbsp; elif data == 'neg':&nbsp; &nbsp; &nbsp; &nbsp; if output.get('1.0', '1.1') != '-':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output.insert('1.0', '-')&nbsp; &nbsp; elif data in 'CE':&nbsp; &nbsp; &nbsp; &nbsp; if 'C' in data:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output.delete('1.0', 'end')&nbsp; &nbsp; &nbsp; &nbsp; if 'E' in data:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; #clear your storage&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pass #delete this linebtn = dict(width=7, height=3)pad = dict(padx=5, pady=5)#all of your buttonsfor i, t in enumerate(['pos', 'neg', 'C', 'CE', '7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '.', '+', '=']):&nbsp; &nbsp; tk.Button(window, text=t, command=lambda d=t: calc(d), **btn).grid(row=i//4+1, column=i%4, **pad)#run calculatorwindow.mainloop()我根据刚才给你的例子制作了一个完全可用的 OOP 版本的计算器。它可能并不完美。我只花了 10 分钟。我添加了键绑定,因此您不必单击按钮。你可以扩展它,从中学习,忽略它......任何让你开心的事情。import tkinter as tkclass App(tk.Tk):&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; tk.Tk.__init__(self)&nbsp; &nbsp; &nbsp; &nbsp; self.oper&nbsp; &nbsp;= ['/', '*', '-', '+']&nbsp; &nbsp; &nbsp; &nbsp; self.queue&nbsp; = []&nbsp; &nbsp; &nbsp; &nbsp; self.result = 0&nbsp; &nbsp; &nbsp; &nbsp; self.equate = False&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; self.output = tk.Text(self, font='Consolas 18 bold', height=2, width=20, wrap='word')&nbsp; &nbsp; &nbsp; &nbsp; self.output.grid(row=0, column=0, columnspan=4, pady=8, padx=4)&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; btn = dict(width=6, height=3, font='Consolas 12 bold')&nbsp; &nbsp; &nbsp; &nbsp; pad = dict(pady=2)&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; special = dict(neg='<Shift-Key-->',pos='<Shift-Key-+>',C='<Key-Delete>',CE='<Key-End>')&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; for i, t in enumerate(['pos', 'neg', 'C', 'CE', '7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '.', '+', '=']):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tk.Button(self, text=t, command=lambda d=t: self.calc(d), **btn).grid(row=i//4+1, column=i%4, **pad)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if t.isnumeric() or t in self.oper or t == '.':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.bind_all(f'<Key-{t}>', lambda e, d=t: self.calc(d))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; elif t == '=':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.bind_all('<Return>', lambda e, d=t: self.calc(d))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.bind_all(special[t], lambda e, d=t: self.calc(d))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; def calc(self, input):&nbsp; &nbsp; &nbsp; &nbsp; print(input)&nbsp; &nbsp; &nbsp; &nbsp; if input.isnumeric() or input == '.':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.output.insert('end', input)&nbsp; &nbsp; &nbsp; &nbsp; elif input == 'pos':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if self.output.get('1.0', '1.1') == '-':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;self.output.delete('1.0', '1.1')&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; elif input == 'neg':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if self.output.get('1.0', '1.1') != '-':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;self.output.insert('1.0', '-')&nbsp; &nbsp; &nbsp; &nbsp; elif input in self.oper and (t := self.output.get('1.0', 'end-1c')):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if not self.equate:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.queue.append(t)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.queue.append(input)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.output.delete('1.0', 'end')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.equate = False&nbsp; &nbsp; &nbsp; &nbsp; elif input == '=' and len(self.queue):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.equate = True&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if self.queue[-1] in self.oper:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.queue.append(self.output.get('1.0', 'end-1c'))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; elif len(self.queue) > 2:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.queue = self.queue+self.queue[-2:]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.result = str(eval(' '.join(self.queue)))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.output.delete('1.0', 'end')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.output.insert('end', self.result)&nbsp; &nbsp; &nbsp; &nbsp; elif input in 'CE':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if 'C' in input:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.output.delete('1.0', 'end')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if 'E' in input:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.queue = []&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if __name__ == '__main__':&nbsp; &nbsp; app = App()&nbsp; &nbsp; app.title('Calcsturbator')&nbsp; &nbsp; app.resizable(width=False, height=False)&nbsp; &nbsp; app.mainloop()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python