In: Computer Science
NEED TO REWRITE THIS IN OOP MODE
######## HOMEWORK 19
###### Rewrite the code in the OOP mode (class mode).
########################### lambda trick
##### first: changing label properties: after you've created a
label, you
##### may want to change something about it. To do that, use
configure method:
## label.configure(text = 'Yes')
## label.configure(bg = 'white', fg = 'black')
### that change the properties of a label called label.
###################################################
##
from tkinter import *
abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def callback(x):
label.configure(text = 'Button {} clicked'. format(abc[x]))
root = Tk()
label = Label()
label.grid(row = 1, column = 0, columnspan = 26)
buttons = [0]*26 ##create a list to hold 26 buttons
for i in range(26):
buttons[i] = Button(text = abc[i],
command = lambda x = i: callback(x))
buttons[i].grid(row = 0, column = i)
mainloop()
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
Note: Please maintain proper code spacing (indentation), just copy the code part and paste it in your compiler/IDE directly, no modifications required.
#code
from tkinter import * ''' class to represent the required GUI ''' class GUI: #constructor def __init__(self): #declaring all instance variables self.__root=Tk() self.__label=Label() #adding created label to the root window self.__label.grid(row=1, column=0, columnspan=26) self.__buttons=[] #setting up buttons self.__setup_buttons() #method to set up the buttons def __setup_buttons(self): #creating a list to store all alphabets letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' #looping through each index for i in range(len(letters)): #creating button with text=current letter, adding command to call self.__callback method btn=Button(self.__root,text=letters[i],command = lambda x=i: self.__callback(x)) #adding button to GUI btn.grid(row = 0, column = i) #adding button to list self.__buttons.append(btn) #event handler method def __callback(self,x): #getting text from button at x index and displaying on the label self.__label.configure(text='Button {} clicked'.format(self.__buttons[x]['text'])) #method to make the window visible def set_visible(self): self.__root.mainloop() #main module if __name__ == '__main__': # creating a GUI and making window visible gui = GUI() gui.set_visible()
#output