[Tutor] How to shorten this code using classes?

Mic o0MB0o at hotmail.se
Wed Nov 23 21:38:18 CET 2011


>I chose to ignore the "using classes" part. If you like you can turn the
>button_clicked() function into a method of a subclass of Button. You can
>also move the Button configuration done in create_widgets() into the
>__init__() method of that subclass.

import tkinter as tk
from functools import partial

def button_clicked(button):
    if button["bg"] == "green":
        button.configure(bg="red", text="Hi 2")
    else:
        button.configure(bg="green", text="Hi 1")

class Window(tk.Frame):
    def __init__(self, master):
        super (Window, self).__init__(master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        for _ in range(2):
            button = tk.Button(self)
            command = partial(button_clicked, button)
            button["command"] = command
            button.grid()
            command()

root = tk.Tk()
root.title("Test")
root.geometry("200x200")
app = Window(root)
root.mainloop()


___________________________________________________________

A very elegant solution. Much better than my previous one. However, I am a 
bit unfamiliar with your way of
coding, I assume you are used to a version other than Python 3.2? Because, 
never before have I seen either
of those
import tkinter as tk
from functools import partial

I also wonder, if I implement your solution, is there anyway I can place the 
buttons in the program as I would like, or will they be played in a 
straight, vertical row
always?

Also, assume that I have a already have a window with a button in it. If you 
press this button, this window is supposed to open.
So, if I press the button, will this window open? Because I created the 
previous window using
from tkinter import* and not import tkinter as tk.


I hope my English is understandable, because it is not my primary language.
Thanks for your help, it is greatly appreciated!






More information about the Tutor mailing list