[Tutor] Can I shorten this code?
Mic
o0MB0o at hotmail.se
Sat Nov 19 20:01:50 CET 2011
Hi!
I am new to programming and it have recently come to my attention that alot
of my code could be shortened.
I have managed to shorten some of the code, but I ran into a problem with
this piece of code:
#Testing changing color and text on two buttons in a GUI.
from tkinter import*
value1=("green")
click1=1
value2=("green")
click2=1
class Window(Frame):
def __init__(self,master):
super (Window,self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
#Creates hello button1
self.hello_bttn1=Button(self,bg=value1)
self.hello_bttn1["text"]="Hi_1"
self.hello_bttn1["command"]=self.change_value_hellobttn1
self.hello_bttn1.grid()
#Creates hello button2
self.hello_bttn2=Button(self,bg=value2)
self.hello_bttn2["text"]="Hi_1"
self.hello_bttn2["command"]=self.change_value_hellobttn2
self.hello_bttn2.grid()
def change_value_hellobttn1(self):
def change_click():
global click1
click1*=-1
change_click()
if click1==-1:
self.hello_bttn1.configure(bg="red")
self.hello_bttn1.configure(text="Hi_2")
def change_global1():
global value1
value1=("red")
change_global1()
elif click1==1:
self.hello_bttn1["text"]="Hi_1"
self.hello_bttn1.configure(bg="green")
def change_global2_1():
global value1
value1=("green")
change_global2_1()
#-------------------------------------------------
def change_value_hellobttn2(self):
def change_click2():
global click2
click2*=-1
change_click2()
if click2==-1:
self.hello_bttn2.configure(bg="red")
self.hello_bttn2.configure(text="Hi_2")
def change_global2():
global value2
value2=("red")
change_global2()
elif click2==1:
self.hello_bttn2["text"]="Hi_1"
self.hello_bttn2.configure(bg="green")
def change_global2_2():
global value2
value2=("green")
change_global2_2()
Imagine now that I want to do the same thing with 8 buttons, that I did to
these two buttons. How would I shorten this?
Otherwise I repeat a lot of my code, and I would like to avoid that.
Thank you!
root=Tk()
root.title("Test")
root.geometry("200x200")
app=Window(root)
root.mainloop()
More information about the Tutor
mailing list