Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from tkinter import (Tk, BOTH, Button, Entry,
- Event, Frame, NSEW, RIGHT, StringVar)
- ## -- START OF CONFIG --
- DISPLAY_FONT = ("Arial", 24)
- BUTTON_FONT = ("Arial", 16)
- WINDOW_DIMENSIONS = "512x384"
- ## -- END OF CONFIG --
- ## Creating the window.
- window = Tk()
- window.geometry(WINDOW_DIMENSIONS)
- ## Creating the main frame to expand with resizing.
- frame = Frame(window)
- ## Setting up the statement display.
- stream = StringVar(frame, name="stream")
- entry = Entry(frame, textvariable=stream, font=DISPLAY_FONT, justify=RIGHT,
- state="readonly", readonlybackground="Blue", foreground="White")
- entry.grid(row=0, column=0, columnspan=5, sticky=NSEW)
- ## Defining functions for handling all key creation and callbacks.
- def handle_key(event):
- if event.keysym == "Escape" or event.char == "CLR":
- window.call("set", "stream", "")
- elif event.keysym == "Return" or event.char == '=':
- try:
- window.call("set", "stream", eval(stream.get().replace('x', '*')))
- except:
- window.call("set", "stream", "ERROR")
- elif event.keysym == "BackSpace":
- window.call("set", "stream", stream.get()[:-1])
- elif event.char == '*':
- window.call("append", "stream", 'x')
- else:
- window.call("append", "stream", event.char)
- def add_button(key, row, column, binding, **kwargs):
- event = Event()
- event.keysym, event.char = "", key
- button = Button(frame, text=key, font=BUTTON_FONT,
- command=lambda: handle_key(event))
- button.grid(row=row, column=column, sticky=NSEW, **kwargs)
- window.bind(binding, handle_key)
- def construct_row_column(num):
- row, column = divmod(num, 3)
- return (row + 1, column - 1) if column != 0 else (row, column + 2)
- ## Adding number keys into the frame.
- for i in range(1, 10):
- row, column = construct_row_column(i)
- add_button(str(i), row, column, str(i))
- ## Adding operation keys into the frame.
- add_button('x', 1, 3, '*')
- add_button('+', 2, 3, '+')
- add_button('-', 3, 3, '-')
- add_button('CLR', 4, 0, "<Escape>")
- add_button('0', 4, 1, '0')
- add_button('.', 4, 2, '.')
- add_button('=', 4, 3, "<Return>", columnspan=2)
- add_button('/', 1, 4, '/')
- add_button('(', 2, 4, '(')
- add_button(')', 3, 4, ')')
- window.bind("<BackSpace>", handle_key)
- ## Configuring cells to autoscale.
- frame.pack(fill=BOTH, expand=True)
- frame.grid_columnconfigure((0, 1, 2, 3, 4), weight=1)
- frame.grid_rowconfigure((0, 1, 2, 3, 4), weight=1)
- ## Run the frame.
- window.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement