Tiny Tkinter Calculator (Python)

Please support our Python advertiser: Programming Forums
Dec 8th, 2006
Views: 4,687
Thread Rating: 2 votes, 4.0000 average.
AddThis Social Bookmark Button
Just a relatively simple calculator using the Tkinter GUI. It has a few nice features such as correcting division by an integer (for older Python versions), error trapping, to and from memory buttons, and an editable display. The editable display allows you to backspace mistakes, and also to enter things not on the key pad, like hexnumbers. For instance if you enter 0xFF and press equals, it will give you the decimal (denary) equivalent of 255

The program also has a guard against the bad guys that like to abuse the underlying eval() function to wipe out files.

I wrote the code in detail, so you can hopefully figure it out. You can fancy up the calculator quite a bit, just experiment with the code.
Last edited : Mar 31st, 2007.
python Syntax
  1. # a tiny/simple Tkinter calculator (improved v.1.1)
  2. # if you enter a number with a leading zero it will be an octal number!
  3. # eg. 012 would be a decimal 10 (0.12 will not be affected)
  4. # used a more modern import to give Tkinter items a namespace
  5. # tested with Python24 vegaseat 08dec2006
  6.  
  7. """
  8. calculator has a layout like this ...
  9. < display >
  10. 7 8 9 * C
  11. 4 5 6 / M->
  12. 1 2 3 - ->M
  13. 0 . = + neg
  14. """
  15.  
  16. import Tkinter as tk
  17.  
  18. def click(key):
  19. global memory
  20. if key == '=':
  21. # avoid division by integer
  22. if '/' in entry.get() and '.' not in entry.get():
  23. entry.insert(tk.END, ".0")
  24. # guard against the bad guys abusing eval()
  25. str1 = "-+0123456789."
  26. if entry.get()[0] not in str1:
  27. entry.insert(tk.END, "first char not in " + str1)
  28. # here comes the calculation part
  29. try:
  30. result = eval(entry.get())
  31. entry.insert(tk.END, " = " + str(result))
  32. except:
  33. entry.insert(tk.END, "--> Error!")
  34. elif key == 'C':
  35. entry.delete(0, tk.END) # clear entry
  36. elif key == '->M':
  37. memory = entry.get()
  38. # extract the result
  39. if '=' in memory:
  40. ix = memory.find('=')
  41. memory = memory[ix+2:]
  42. root.title('M=' + memory)
  43. elif key == 'M->':
  44. entry.insert(tk.END, memory)
  45. elif key == 'neg':
  46. if '=' in entry.get():
  47. entry.delete(0, tk.END)
  48. try:
  49. if entry.get()[0] == '-':
  50. entry.delete(0)
  51. else:
  52. entry.insert(0, '-')
  53. except IndexError:
  54. pass
  55. else:
  56. # previous calculation has been done, clear entry
  57. if '=' in entry.get():
  58. entry.delete(0, tk.END)
  59. entry.insert(tk.END, key)
  60.  
  61. root = tk.Tk()
  62. root.title("Simple Calculator")
  63.  
  64. btn_list = [
  65. '7', '8', '9', '*', 'C',
  66. '4', '5', '6', '/', 'M->',
  67. '1', '2', '3', '-', '->M',
  68. '0', '.', '=', '+', 'neg' ]
  69.  
  70. # create all buttons with a loop
  71. r = 1
  72. c = 0
  73. for b in btn_list:
  74. rel = 'ridge'
  75. cmd = lambda x=b: click(x)
  76. tk.Button(root,text=b,width=5,relief=rel,command=cmd).grid(row=r,column=c)
  77. c += 1
  78. if c > 4:
  79. c = 0
  80. r += 1
  81.  
  82. # use Entry widget for an editable display
  83. entry = tk.Entry(root, width=33, bg="yellow")
  84. entry.grid(row=0, column=0, columnspan=5)
  85.  
  86. root.mainloop()
vegaseat | DaniWeb's Hypocrite | Mar 26th, 2007
Simplified the code by creating all the buttons in a loop. Hope you can still follow the flow.  

Only community members can submit or comment on code snippets. You must register or log in to contribute.

Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 1:59 pm.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC