亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何正確地將我在計算器中按下的數字插入到最后一個索引處的文本小部件中?

如何正確地將我在計算器中按下的數字插入到最后一個索引處的文本小部件中?

人到中年有點甜 2023-05-16 09:50:42
例如,當我按下“100”時,在文本框中輸出“001”。我嘗試在索引中使用 -1 但同樣的事情仍然發生,我也嘗試執行 .insert(0.end, num) 但它會引發錯誤。我怎樣才能讓數字總是在輸出的末尾輸入。此外,這是使用 tkinter 輸出數字的最佳方式還是有其他方式?from tkinter import *import operatorwindow = Tk()window.title('Calculator')def click(num):    output.insert(0.0, num) #numbers not properly inputted (bug)#output for calculatoroutput = 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 operatorsb_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))#numbersb_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))
查看完整描述

2 回答

?
慕哥9229398

TA貢獻1877條經驗 獲得超6個贊

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

output.insert("end", num)

來自官方文檔:

end - 表示條目字符串中最后一個字符之后的字符。這相當于指定一個等于條目字符串長度的數字索引。


查看完整回答
反對 回復 2023-05-16
?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

你工作太辛苦了。從圖形的角度來看,您必須考慮到您的按鈕都是完全相同的東西。您只需幾行就可以構建整個界面。由于每個按鈕都會調用calc,只需編寫條件語句來calc處理各種可能性。您可以在該函數中構建計算器的全部功能。


import tkinter as tk 


window = tk.Tk()

window.title('Calculator')


#output for calculator

output = 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):

    if data.isnumeric() or data == '.':

        output.insert('end', data)

    elif data in ['-', '+', '*', '/']:

        #write code for handling operators

        pass #delete this line

    elif data == '=':

        #write code for handling equals

        pass #delete this line

    elif data == 'pos':

        if output.get('1.0', '1.1') == '-':

            output.delete('1.0', '1.1') 

    elif data == 'neg':

        if output.get('1.0', '1.1') != '-':

            output.insert('1.0', '-')

    elif data in 'CE':

        if 'C' in data:

            output.delete('1.0', 'end')

        if 'E' in data:

            #clear your storage

            pass #delete this line


btn = dict(width=7, height=3)

pad = dict(padx=5, pady=5)


#all of your buttons

for i, t in enumerate(['pos', 'neg', 'C', 'CE', '7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '.', '+', '=']):

    tk.Button(window, text=t, command=lambda d=t: calc(d), **btn).grid(row=i//4+1, column=i%4, **pad)


#run calculator

window.mainloop()

我根據剛才給你的例子制作了一個完全可用的 OOP 版本的計算器。它可能并不完美。我只花了 10 分鐘。我添加了鍵綁定,因此您不必單擊按鈕。你可以擴展它,從中學習,忽略它......任何讓你開心的事情。


import tkinter as tk


class App(tk.Tk):

    def __init__(self):

        tk.Tk.__init__(self)

        self.oper   = ['/', '*', '-', '+']

        self.queue  = []

        self.result = 0

        self.equate = False

        

        self.output = tk.Text(self, font='Consolas 18 bold', height=2, width=20, wrap='word')

        self.output.grid(row=0, column=0, columnspan=4, pady=8, padx=4)

        

        btn = dict(width=6, height=3, font='Consolas 12 bold')

        pad = dict(pady=2)

        

        special = dict(neg='<Shift-Key-->',pos='<Shift-Key-+>',C='<Key-Delete>',CE='<Key-End>')

        

        for i, t in enumerate(['pos', 'neg', 'C', 'CE', '7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '.', '+', '=']):

            tk.Button(self, text=t, command=lambda d=t: self.calc(d), **btn).grid(row=i//4+1, column=i%4, **pad)

            if t.isnumeric() or t in self.oper or t == '.':

                self.bind_all(f'<Key-{t}>', lambda e, d=t: self.calc(d))

            elif t == '=':

                self.bind_all('<Return>', lambda e, d=t: self.calc(d))

            else:

                self.bind_all(special[t], lambda e, d=t: self.calc(d))

                

    def calc(self, input):

        print(input)

        if input.isnumeric() or input == '.':

            self.output.insert('end', input)

        elif input == 'pos':

            if self.output.get('1.0', '1.1') == '-':

               self.output.delete('1.0', '1.1') 

        elif input == 'neg':

            if self.output.get('1.0', '1.1') != '-':

               self.output.insert('1.0', '-')

        elif input in self.oper and (t := self.output.get('1.0', 'end-1c')):

            if not self.equate:

                self.queue.append(t)

            self.queue.append(input)

            self.output.delete('1.0', 'end')

            self.equate = False

        elif input == '=' and len(self.queue):

            self.equate = True

            if self.queue[-1] in self.oper:

                self.queue.append(self.output.get('1.0', 'end-1c'))

            elif len(self.queue) > 2:

                self.queue = self.queue+self.queue[-2:]

                    

            self.result = str(eval(' '.join(self.queue)))

            self.output.delete('1.0', 'end')

            self.output.insert('end', self.result)

        elif input in 'CE':

            if 'C' in input:

                self.output.delete('1.0', 'end')

            if 'E' in input:

                self.queue = []

            

                    

if __name__ == '__main__':

    app = App()

    app.title('Calcsturbator')

    app.resizable(width=False, height=False)

    app.mainloop()


查看完整回答
反對 回復 2023-05-16
  • 2 回答
  • 0 關注
  • 164 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號