Let’s take a look at the renderings first
Calculator rendering
The following code
import math from tkinter import * def add_word(c): if c == '=': TXT. Replace (' 0.0 ', 'end', eval (TXT. Get (' 0.0 ', 'end'))) # fill the results the else: Def handler(fun, c): return lambda fun=fun, c=c: Fun (c) the root = Tk (root). The title (" calculator ") text_arr = [' 1 ', '2', '3', '+', '4', '5', '6', '-', '7', '8', '9', '*', '. ', '0' and '=', '/'] Ncol, bw, bh, padding, space, th = 4,50,30,20,10,100 # button number of columns, buttons, width, height, page margin, margin between button, text box height nrow = math.h ceil (len (text_arr) * 1.0 / ncol) Geometry ("%sx%s" % (bw*ncol + padding*2 + space*(ncol-1), th + bh*nrow + padding*3 + space*(nrow-1))) txt = Text(root) txt.place(x=padding,y=padding,width=bw*ncol+space*(ncol-1),height=th) for index in range(len(text_arr)): Row_index, col_index = (index%ncol), (index//ncol) # BTN = Button(root, text=text_arr[index], command=handler(add_word, text_arr[index])) btn.place(x=padding+row_index*(bw+space), y=(th+padding*2)+col_index*(bh+space), width=bw, height=bh) root.mainloop()Copy the code
Modifying the width, height, and margin of a button does not affect the interface layout.
Add or subtract the text_arr button
text_arr=['(',')','**','%','1','2','3','+','4','5','6','-','7','8','9','*','.','0','=','/']
Copy the code
The computer can be used normally, and the interface will look like the following
Modified interface
The code does not handle exception input. If you add button text or function buttons that Eval cannot support, you need to do special processing in add_word.
Learn more about Python by programming at your fingertips.