[Tutor] Shortening the code

ALAN GAULD alan.gauld at btinternet.com
Sat Nov 26 17:05:35 CET 2011



>> How are you running the code?
> I am running it inside an IDLE. Does it matter 

IDLE sometimes slows things down and can occasionally lock 
up with Tkinter (probably because it is itself written in Tkinter!). 
It's usually better and faster  to run Tkinter programs from a separate 
console window.

class SeatButton(tk.Button):
           def clicked(self):
               self.occupied = not self.occupied
               if self.occupied:
                   self["bg"] = OCCUPIED
                   ###################################
                   text_file=open(self.filename,"w")
                   text_file.write(self.filename)
                   text_file.close
                   ###################################
               else:
                   self["bg"] = FREE
                   ################################
                   os.remove(self.filename)
                   #################################

OK, I see.

> As you can see, if button one it pressed it creates a file with the name 
>Germany_France1
> and with the contents Germany_France1 . If it is pressed once more, it removes 
>the file.

> I wonder, do you know how I can do this in your piece of code? 

What you are doing is fine, I'd leave the button click bit as it is if you 
really want to 
create/delete files. As I said originally this is an unusual thing to do but you 
may 
have more going on behind the scenes or planned.

But normally I would just keep all the data about whether the seats were booked 
or 
not in memory and then save it all in one go into a single file at the end of 
the program.
Or, for a long running program, I might store it in a file but I'd use a single 
file - probably 
a shelve file. (If you are not familiar with shelves they are special files that 
act like
 dictionaries in your code.)

HTH,

Alan G.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111126/0760aa8e/attachment.html>


More information about the Tutor mailing list