God morning!
That's right, because your SeatButton init doesn't check to see if a
file exists for it, it always colors it green. You need to read the
directory and see whether a file for that seat exists. If it does
color it red. (Hint: look at os.path.exists() )
Alright, I think I now managed to solve this problem. Here is the code:
from tkinter import*
import tkinter as tk
import os
FREE = "green"
OCCUPIED = "red"
class Mainwindow(Frame):
def __init__(self,master):
super(Mainwindow,self).__init__(master)
self.grid()
self.create_mainwidgets()
def create_mainwidgets(self):
self.klicka=Button(self, text="Press the button",
command=self.uppdatera)
self.klicka.grid()
def uppdatera(self):
SeatWindow(root)
class SeatButton(tk.Button):
def __init__(self, master, index):
text = str(index+1)
super(SeatButton, self).__init__(master,
text=text, bg=FREE,
command=self.clicked)
self.filename = "Germany_France{}.txt".format(index+1)
self.occupied = False
if os.path.exists(self.filename):
self["bg"]=OCCUPIED
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)
class SeatWindow(tk.Toplevel):
def __init__(self, master):
super (SeatWindow, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
for index in range(20):
button = SeatButton(self, index)
row, column = divmod(index, 4)
button.grid(row=row, column=column)
root=Tk()
root.title("testV2")
app=Mainwindow(root)
root.mainloop()
This is one case where I think it will be easier to show you than tell
you so I've pasted my modified version of your code. Note that I've
moved all the clsses to the outer level and made the second window(which
I've renamed SeatWindow) inherit from Toplevel rather than Frame so that
you can create it as a child of the Mainwindow. That then allows a
single mainloop. It will be worth while studying the differences to see
if you understand why I've done what I've done.
Yeah, well, the main difference I can see is that you only uses one tk
object while I used more. Hmm, otherwise I can see that you have bound the
button in the main window to the function
def uppdatera(self):
SeatWindow(root)
which opens the SeatWindow right? I probably missed things, but I noticed
that this is much smoother than my alternative!
Thanks !
Mic
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor