-
-
Save kms70847/5274832c4a89ade1d2522ea154ec63aa to your computer and use it in GitHub Desktop.
A comparison of the behavior of two ways of calculating button grid positions, given one fewer button than expected
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#create a grid of buttons using a 1d list of texts, and arithmetic to convert between 2d position and 1d index | |
from tkinter import * | |
root = Tk() | |
root['bg'] = '#1e2936' | |
texts = [ | |
'DEL', 'C', '^2', 'v', | |
'1', '2', '3', '+', | |
'4', '5', '6', #minus button intentionally omitted | |
'7', '8', '9', 'x', | |
'.', '0', '=', '/' | |
] | |
Label(root,text='6*9+6+9',fg='white',font=('',34,'bold'),bg='#1e2936',anchor='e').grid(row=0,column=0,columnspan=4,sticky='news',pady=10) | |
btns = [] | |
img = PhotoImage(width=1,height=1) | |
for text in texts: | |
if text in '1234567890': color = "#10B981" | |
elif text in ('+', '-', 'x', '/', 'v', '^2'): color = "#F59E0B" | |
elif text in "=": color = "#047857" | |
elif text in ("C", "DEL"): color = "#2563EB" | |
btn = Button(root,text=text,bg=color,fg='white',image=img,compound='t',width=100,height=100,relief='flat',highlightcolor='red',font=('',18,'bold')) | |
btns.append(btn) | |
for i in range(5): | |
for j in range(4): | |
if 4*i+j < len(btns): | |
btns[4*i+j].grid(row=i+1,column=j,padx=5,pady=5) | |
root.mainloop() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#create a grid of buttons using a 2d list of texts, with the 2d index corresponding to the final grid position | |
from tkinter import * | |
root = Tk() | |
root['bg'] = '#1e2936' | |
texts = [ | |
['DEL', 'C', '^2', 'v'], | |
['1', '2', '3', '+'], | |
['4', '5', '6'], #minus button intentionally omitted | |
['7', '8', '9', 'x'], | |
['.', '0', '=', '/'] | |
] | |
Label(root,text='6*9+6+9',fg='white',font=('',34,'bold'),bg='#1e2936',anchor='e').grid(row=0,column=0,columnspan=4,sticky='news',pady=10) | |
btns = [] | |
img = PhotoImage(width=1,height=1) | |
for j, row in enumerate(texts): | |
for i, text in enumerate(row): | |
if text in '1234567890': color = "#10B981" | |
elif text in ('+', '-', 'x', '/', 'v', '^2'): color = "#F59E0B" | |
elif text in "=": color = "#047857" | |
elif text in ("C", "DEL"): color = "#2563EB" | |
btn = Button(root,text=text,bg=color,fg='white',image=img,compound='t',width=100,height=100,relief='flat',highlightcolor='red',font=('',18,'bold')) | |
btn.grid(row=j+1, column=i, padx=5, pady=5) | |
btns.append(btn) | |
root.mainloop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment