How to access through all the entry boxes and make them blank - python

As a new python learner, I was trying to create a form in Tkinter with some entry boxes which takes some values from a user. For that I have used For loop to create a 4x2 matrix of entry boxes and filled them with some dummy names.
Now I was wondering how to make all these boxes blank in one shot. The function that I created only makes last entry box blank. I am trying access through all the boxes one by one to make them blank but not able to do.
from tkinter import *
master = Tk()
master.geometry("175x175")
def clear():
e1.delete(0, END)
for y in range(4):
for i in range(2):
e1 = Entry(master)
e1.grid(row = y, column = i, padx = 20, pady= 10)
if y == 0:
if i == 0:
e1.insert(0,'Vishal')
else:
e1.insert(0,'Mishra')
elif y == 1:
if i == 0:
e1.insert(0,'ashish')
else:
e1.insert(0,'Mishra')
elif y == 2:
if i == 0:
e1.insert(0,'vikas')
else:
e1.insert(0,'Mishra')
else:
if i == 0:
e1.insert(0,'sacHin')
else:
e1.insert(0,'Mishra')
btn = Button(master, text = 'Clear', command = clear)
btn.grid(row= 4, column = 1)
master.mainloop()
please suggest..

you are only holding the last Entry you create, you will need to hold all of them. change your code like this:
entries = [] # note these changes
def clear():
for item in entries:
item.delete(0, END)
for y in range(4):
for i in range(2):
e1 = Entry(master)
entries.append(e1) # and this change
e1.grid(row = y, column = i, padx = 20, pady= 10)
if y == 0:
if i == 0:
e1.insert(0,'Vishal')
else:
e1.insert(0,'Mishra')
elif y == 1:
if i == 0:
e1.insert(0,'ashish')
else:
e1.insert(0,'Mishra')
elif y == 2:
if i == 0:
e1.insert(0,'vikas')
else:
e1.insert(0,'Mishra')
else:
if i == 0:
e1.insert(0,'sacHin')
else:
e1.insert(0,'Mishra')

Related

set and image for a canvas when user clicks and when we have multiple canvases on tkinter

I have a code that makes multiple canvases on Python tkinter (9 canvas). With this function (I destroy all item on window with destroy function at start):
def show_board(self):
self.destroy_start()
canvas_list = []
for i in range(9):
dist = {
f"canvas{i + 1}": Canvas(height=150, width=150, bg=BOARD_COLOR),
}
canvas_list.append(dist)
for n in range(len(canvas_list)):
canvas_dict = canvas_list[n]
for (key, val) in canvas_dict.items():
if n == 0 or n <= 2:
row = 0
if n == 0:
col = 0
val.grid(row=row, column=col, padx=(125, 0))
elif n == 1:
col = 1
val.grid(row=row, column=col)
elif n == 2:
col = 2
val.grid(row=row, column=col)
elif 2 < n <= 5:
row = 1
if n == 3:
col = 0
val.grid(row=row, column=col, padx=(125, 0))
elif n == 4:
col = 1
val.grid(row=row, column=col)
elif n == 5:
col = 2
val.grid(row=row, column=col)
elif n > 5:
row = 2
if n == 6:
col = 0
val.grid(row=row, column=col, padx=(125, 0))
elif n == 7:
col = 1
val.grid(row=row, column=col)
elif n == 8:
col = 2
val.grid(row=row, column=col)
# loop in canvas and get x and y of the click and set the image when user click
for item in canvas_list:
for (key, val) in item.items():
canvas_x, canvas_y = val.winfo_rootx(), val.winfo_rooty()
print(canvas_x, canvas_y)
self.check_click(can=val)
self.pl1_score_label.grid(column=0, row=3, padx=(100, 0))
self.pl2_score_label.grid(column=2, row=3)
and I want to when user clicks on window on one of these canvases for the canvas to create an image (just than canvas)
I try to do this with last loop in upper function
def display_mouse_pos(self, event):
self.window.update()
x = event.x
y = event.y
print(x, y)
def check_click(self, can):
self.window.bind("<Button-1>", self.display_mouse_pos)
can.create_image(100, 100, image=self.x_image)
self.window.update()`
but I get that image on all canvas I know problem is my function and for loop I can't find the way to check if screen get clicked or not and if its get clicked which canvas get clicked and who can I make a picture in that canvas

Tkinter - modifying buttons based on rows and columns

I want to change the colour of a button based on its row and column. I am able to search for adjacent buttons, but cant do anything with them. The code is a python version of the board game Othello, and I am trying to get the "sandwiching" aspect of the game to run. Ideally, it stays in the grid system so I am able to code to my ability
from tkinter import *
### Function to change button colour ###
def changeColour(tempButton, row, column):
if tempButton.cget("bg") == "black":
tempButton.configure (bg = "white")
else:
tempButton.configure (bg = "black")
sandwichButton(tempButton, row, column)
### Function to sandwich adjacent buttons ###
def sandwichButton(originButton, row, column):
for x in range (-1,2,1):
for y in range (-1,2,1):
aRow = (row + y)
aColumn = (column + x)
adjacentInfo = find_position(othello, aRow, aColumn)
endButtonInfo = find_position(othello, aRow + y, aColumn + x)
if adjacentInfo["row"] == (aRow) and adjacentInfo["column"] == (aColumn):
adjacentButton = ADJACENT INFORMATION
if endButtonInfo["row"] == (aRow + y) and endButtonInfo["column"] == (aColumn+x):
if originButton.cget("bg") == "black":
adjacentButton.configure (bg = "white")
else:
adjacentButton.configure (bg = "black")
### Function to find button position ###
def find_position(frame, row, column):
for children in frame.children.values():
info = children.grid_info()
if info["row"] == row and info["column"] == column:
return info
break
### Creating the window ###
othello = Tk()
othello.title("Othello Draft 1")
othello.geometry("800x800")
### Creating buttons ###
for r in range (8): #Rows
for c in range(8): #Columns
button = Button(othello, width = 10, height = 5)
button.grid(row = r, column = c)
button.configure (bg = "green", command = lambda buttonName = button, r = r, c = c: changeColour(buttonName, r, c))
### Running the window ###
othello.mainloop()
You could add the buttons to a list and use an if and elif statement to configure the buttons and input your conditions into the if.
for button in [list your buttons here]
if condition:
button.config(command=command(), bg=colour)
elif condition:
button.config(command=command2(), bg=colour2)

Maximum recursion error depth causing crash?

I'm making Minesweeper with tkinter. I want to have it so that when a button with 0 mines surrounding it is clicked, all the buttons around that one are automatically clicked. However, when I run this and click on a button with 0, the program crashes. (originally it gave me the error of "maximum recursion depth exceeded"). How do I fix this? Here is the full code:
import tkinter as tk
import sys
import random
from tkinter import messagebox
from PIL import Image, ImageTk
from types import FunctionType
from copy import copy
app = tk.Tk()
app.geometry("432x468")
app.title("Minesweeper")
sys.setrecursionlimit(999999999)
colors = ['#FFFFFF', '#0000FF', '#008200', '#FF0000', '#000084', '#840000', '#008284', '#840084', '#000000']
# create lists
def createlists():
global buttonlist
global mylist
global numberlist
global panelist
global rightlist
global flaglist
global rowlist
global columnlist
global abomb
global adic
global secondlist
secondlist = []
abomb = []
adic = {}
buttonlist = []
mylist = [0]
numberlist = []
panelist = []
rightlist = []
flaglist = []
rowlist = []
columnlist = []
for a in range(1,18):
mylist.append(18*a)
for i in range(1,325):
button = "b" + str(i)
flag = 'flag' + str(i)
row = 'row' + str(i)
column = 'column' + str(i)
buttonlist.append(button)
numberlist.append(i)
secondlist.append(i)
flaglist.append(flag)
rowlist.append(row)
columnlist.append(column)
# randomly select bombs
def selectbombs():
for i in range(0,50):
x = "panel" + str(bomblist[i])
panelist.append(x)
for i in bomblist:
n = "a" + str(i)
abomb.append(n)
secondlist.remove(i)
# create function for when a bomb is clicked
def mine():
global bomblist
for i in range(0,50):
panelist[i] = tk.Label(app, image = bomb)
for x in mylist:
for i in range(x,x+18):
if i+1 in bomblist:
thing = bomblist.index(i+1)
panelist[thing].grid(row=mylist.index(x)+1, column=i-x+1, columnspan=1)
MsgBox = tk.messagebox.askquestion ('Game Over', 'You clicked on a bomb! Game Over. Would you like to play again?')
if MsgBox == 'no':
app.destroy()
else:
createlists()
bomblist = random.sample(numberlist, 50)
selectbombs()
buttons()
numbers()
flags()
# create grid of buttons
def buttons():
for i in range(0,324):
if i+1 in bomblist:
buttonlist[i] = tk.Button(app, text="", width=2, height=1, command=mine)
else:
buttonlist[i] = tk.Button(app, text="", width=2, height=1)
for x in mylist:
for i in range(x,x+18):
buttonlist[i].grid(row=mylist.index(x)+1, column=i-x+1, columnspan=1)
rowlist[i] = mylist.index(x)+1
columnlist[i] = i-x+1
# determine the number of bombs adjacent to each button
def numbers():
for i in range(1,325):
adic.update({"a"+str(i) : 0})
alist = list(adic)
for i in bomblist:
for x in numberlist:
if rowlist[x-1] in range(rowlist[numberlist.index(i)]-1, rowlist[numberlist.index(i)]+2) and columnlist[x-1] in range(columnlist[numberlist.index(i)]-1, columnlist[numberlist.index(i)]+2):
adic[alist[x-1]] = adic[alist[x-1]] + 1
for i in bomblist:
del adic[alist[numberlist.index(i)]]
alist = list(adic)
for i in adic:
buttonlist[secondlist[alist.index(i)]-1].bind("<Button-1>", lambda event, x=secondlist[alist.index(i)]-1, y=adic[i] : num(x, y))
# number functions
def num(x, y):
a = rowlist[x]
b = columnlist[x]
if y==0:
buttonlist[x].config(bg = '#FFFFFF')
buttonlist[x]["state"] = "disabled"
if a != 1 and b != 1:
num(x-19, adic["a"+str(x-18)])
if a != 1:
num(x-18, adic["a"+str(x-17)])
if a != 1 and b != 18:
num(x-17, adic["a"+str(x-16)])
if b != 1:
num(x-1, adic["a"+str(x)])
if b != 18:
num(x+1, adic["a"+str(x+2)])
if a != 18 and b != 1:
num(x+17, adic["a"+str(x+18)])
if a != 18:
num(x+18, adic["a"+str(x+19)])
if a != 18 and b != 18:
num(x+19, adic["a"+str(x+20)])
else:
buttonlist[x].config(text = y, disabledforeground = colors[y], bg = '#FFFFFF')
buttonlist[x]["state"] = "disabled"
# create function to place a flag
im = Image.open("flag.png")
im = im.resize((20,20), Image.ANTIALIAS)
flag = ImageTk.PhotoImage(im)
def flags():
for i in range(0,324):
buttonlist[i].bind("<Button-3>", lambda event, x=i : right(event, x))
def right(event, x):
if buttonlist[x]["state"] == "normal":
flaglist[x] = tk.Button(app, text = "", width=18, height=19, image = flag)
flaglist[x].grid(row=rowlist[x], column=columnlist[x], columnspan=1)
flaglist[x].bind("<Button-1>", lambda event: flaglist[x].destroy())
# check if the game has been won
def checkwin():
disnum = 0
for i in secondlist:
if buttonlist[i-1]["state"] == "disabled":
disnum = disnum + 1
if disnum == 274:
MsgBox = tk.messagebox.askquestion ('Game Won', 'You have won the game! Would you like to play again?')
if MsgBox == 'no':
app.destroy()
else:
createlists()
bomblist = random.sample(numberlist, 50)
selectbombs()
buttons()
numbers()
flags()
# open images
img = Image.open("bomb.png")
img = img.resize((20,20), Image.ANTIALIAS)
bomb = ImageTk.PhotoImage(img)
createlists()
bomblist = random.sample(numberlist, 50)
selectbombs()
buttons()
numbers()
flags()
app.mainloop()
the specific part which is causing the program to crash:
def num(x, y):
a = rowlist[x]
b = columnlist[x]
if y==0:
buttonlist[x].config(bg = '#FFFFFF')
buttonlist[x]["state"] = "disabled"
if a != 1 and b != 1:
num(x-19, adic["a"+str(x-18)])
if a != 1:
num(x-18, adic["a"+str(x-17)])
if a != 1 and b != 18:
num(x-17, adic["a"+str(x-16)])
if b != 1:
num(x-1, adic["a"+str(x)])
if b != 18:
num(x+1, adic["a"+str(x+2)])
if a != 18 and b != 1:
num(x+17, adic["a"+str(x+18)])
if a != 18:
num(x+18, adic["a"+str(x+19)])
if a != 18 and b != 18:
num(x+19, adic["a"+str(x+20)])
else:
buttonlist[x].config(text = y, disabledforeground = colors[y], bg = '#FFFFFF')
buttonlist[x]["state"] = "disabled"
The issue is that in the recursion process, the code is backtracking on previous squares. When checking a new square, be sure it has not already be checked.
In the num function, add a line of code to skip squares that have already been disabled:
def num(x, y):
if buttonlist[x]["state"] == "disabled": return # add this line
a = rowlist[x]
b = columnlist[x]

issue with filling the correct grid cell in tkinter

im trying to make a battleship game in python using tkinter,
the minimum reproducible example is:
from tkinter import *
from random import randint
import time
tk = Tk()
class player:
def __init__(self, master):
self.master = master
self.placedships = []
self.bombed = []
self.sunk = []
self.ship_sizes = [5, 4, 3]
self.player_canvas = Canvas(master, height=300, width=300, highlightbackground='black', highlightthickness=0.5)
self.ai_canvas = Canvas(master, height=300, width=300, highlightbackground='black', highlightthickness=0.5)
self.player_canvas.grid(row=1, column=0, padx=50)
self.ai_canvas.grid(row=1, column=1, padx=50)
self.direction = 'v'
self.shipChosen = 0
gridLabel_player = Label(master,text="Your grid \nA B C D E F G H I J ")
gridLabel_player.grid(row=0,column=0)
gridLabel_ai = Label(master,text="AI's grid \nA B C D E F G H I J ")
gridLabel_ai.grid(row=0,column=1)
for x in range(10):
for y in range(10):
self.player_canvas.create_rectangle(x * 30, y * 30, 300, 300, fill = 'white')
self.ai_canvas.create_rectangle(x * 30, y * 30, 300, 300, fill = 'white')
#variables to store data for cells on game grid
# # self.player_ocean = 10 * [10 * [0]]
# # self.ai_ocean = 10 * [10 * [0]]
self.player_ocean = []
self.ai_ocean = []
temp = []
for i in range(10):
for y in range(10):
temp += [0]
self.player_ocean += [temp]
self.ai_ocean += [temp]
temp = []
self.selectedCoord = [0,0] # [0] = x coord, [1] = y coord
def placeShip(self):
def moveShip(event):
if event.keysym == 'Down' and self.selectedCoord[1] != 9:
self.selectedCoord[1] += 1
elif event.keysym == 'Up' and self.selectedCoord[1] != 0:
self.selectedCoord[1] -= 1
elif event.keysym == 'Left' and self.selectedCoord[0] != 0:
self.selectedCoord[0] -= 1
elif event.keysym == 'Right' and self.selectedCoord[0] != 9:
self.selectedCoord[0] += 1
print('selected coord:',self.selectedCoord)
def selectPlacement(event):
col = self.selectedCoord[0]
row = self.selectedCoord[1]
if self.direction == 'v':
v_range_start = row - self.ship_sizes[self.shipChosen] + 1
for y in range(v_range_start, row+1):
'''insert validation to reject ship clashing'''
self.player_ocean[y][col] = 1
self.placedships += [y,col]
self.refresh_ocean()
self.master.bind("<Up>", moveShip)
self.master.bind("<Down>", moveShip)
self.master.bind("<Left>", moveShip)
self.master.bind("<Right>", moveShip)
self.master.bind("<Return>", selectPlacement)
def refresh_ocean(self): # 1s turns to green
for y in range(10):
for x in range(10):
if self.player_ocean[y][x] == 1:
self.player_canvas.itemconfig(self.player_canvas.create_rectangle( (x+1) * 30, (y-1) * 30,x * 30, y * 30, fill='green'))
player1 = player(tk)
player1.placeShip()
tk.mainloop()
the problem i have is that lets say if i press the down arrow until my selected coordinate is [0,9], the code should colour the 6th to 10th box from top down, in the first column, but it colours the 5th to 9th box.
i have tried debugging it by checking if the coordinates x and y used in the last function refresh_ocean were wrong, but they were as expected
So the short and simple fix is to change (y-1) to (y+1).
That said I made a few changes:
Rewrote some of your names to follow PEP8 style guide.
Converted your refresh_ocean method to handle the initial draw and all draws afterwords. As well as added a delete('all') to clear the board so we are not draw on top of the previous objects. This will prevent using up more memory as the game progresses.
Cleaned up imports and changed from tkinter import * to import tkinter as tk. This will help prevent overwriting other things in the namespace.
By writing your refresh_ocean to handle all the drawing we can specify what needs to be drawn with tags like 'player1' and 'ai'.
Changed += to .append() for your list generation as append() is twice as fast as '+=. See this post: Difference between “.append()” and “+= []”?
Changed you single label of headers into a loop to create each label evenly. This will allow for a more accurate header then trying to manually set spaces in a single string.
Lastly because you are already checking of the key is one of the 4 arrow keys we can use a single bind to '<Key>' and get the same results as all 4 binds.
Updated code:
import tkinter as tk
class Player(tk.Tk):
def __init__(self):
super().__init__()
self.placed_ships = []
self.player_ocean = []
self.ai_ocean = []
self.bombed = []
self.sunk = []
self.bord_size = list('ABCDEFGHIJ')
self.selected_coord = [0, 0]
self.ship_sizes = [5, 4, 3]
self.direction = 'v'
self.shipChosen = 0
wh = 300
p_label_frame = tk.Frame(self, width=wh, height=30)
a_label_frame = tk.Frame(self, width=wh, height=30)
p_label_frame.grid(row=1, column=0, padx=50)
a_label_frame.grid(row=1, column=1, padx=50)
p_label_frame.grid_propagate(False)
a_label_frame.grid_propagate(False)
for ndex, letter in enumerate(self.bord_size):
p_label_frame.columnconfigure(ndex, weight=1)
a_label_frame.columnconfigure(ndex, weight=1)
tk.Label(p_label_frame, text=letter).grid(row=0, column=ndex)
tk.Label(a_label_frame, text=letter).grid(row=0, column=ndex)
self.player_canvas = tk.Canvas(self, height=wh, width=wh, highlightbackground='black', highlightthickness=0.5)
self.ai_canvas = tk.Canvas(self, height=wh, width=wh, highlightbackground='black', highlightthickness=0.5)
self.player_canvas.grid(row=2, column=0, padx=50)
self.ai_canvas.grid(row=2, column=1, padx=50)
temp = []
for i in range(10):
for y in range(10):
temp.append(0)
self.player_ocean.append(temp)
self.ai_ocean.append(temp)
temp = []
self.refresh_ocean()
self.bind("<Key>", self.move_ship)
self.bind("<Return>", self.select_placement)
def move_ship(self, event):
if event.keysym == 'Down' and self.selected_coord[1] < 9:
self.selected_coord[1] += 1
elif event.keysym == 'Up' and self.selected_coord[1] > 0:
self.selected_coord[1] -= 1
elif event.keysym == 'Left' and self.selected_coord[0] > 0:
self.selected_coord[0] -= 1
elif event.keysym == 'Right' and self.selected_coord[0] < 9:
self.selected_coord[0] += 1
print('selected coord:', self.selected_coord)
def select_placement(self, _=None):
col = self.selected_coord[0]
row = self.selected_coord[1]
if self.direction == 'v':
v_range_start = row - self.ship_sizes[self.shipChosen] + 1
for y in range(v_range_start, row+1):
'''insert validation to reject ship clashing'''
self.player_ocean[y][col] = 1
self.placed_ships += [y, col]
self.refresh_ocean(side='player1')
def refresh_ocean(self, side=None):
self.player_canvas.delete('all')
self.ai_canvas.delete('all')
for y in range(len(self.bord_size)):
for x in range(len(self.bord_size)):
if self.player_ocean[y][x] == 1 and side == 'player1':
self.player_canvas.itemconfig(self.player_canvas.create_rectangle(
(x+1) * 30, (y+1) * 30, x * 30, y * 30, fill='green'))
else:
self.player_canvas.create_rectangle(x * 30, y * 30, 300, 300, fill='white')
if self.ai_ocean[y][x] == 1 and side == 'ai':
self.ai_canvas.itemconfig(self.ai_canvas.create_rectangle(
(x + 1) * 30, (y + 1) * 30, x * 30, y * 30, fill='green'))
else:
self.ai_canvas.create_rectangle(x * 30, y * 30, 300, 300, fill='white')
if __name__ == '__main__':
Player().mainloop()
Results:
your refresh_ocean had an off by 1 error
def refresh_ocean(self): # 1s turns to green
for y in range(10):
for x in range(10):
if self.player_ocean[y][x] == 1:
self.player_canvas.itemconfig(self.player_canvas.create_rectangle( x*30, y * 30, x*30+30, y*30+30, fill='green'))
and select placement was placing ships in with a negative index.
i changed your iteration from range(row-size, row) to range(row, row+size) and added bounds checking, but that should probably be moved to the movement handling.
def selectPlacement(event):
col = self.selectedCoord[0]
row = self.selectedCoord[1]
if self.direction == 'v':
if row + self.ship_sizes[self.shipChosen] > 9:
row = 10 - self.ship_sizes[self.shipChosen]
for y in range(row, row + self.ship_sizes[self.shipChosen]):
'''insert validation to reject ship clashing'''
self.player_ocean[y][col] = 1
self.placedships += [y,col]
self.refresh_ocean()
ps: your drawing new squares on top of the old squares. you might want to clear the ocean before drawing.

Python Tkinter 2 classes

I have 2 classes, i create the instance of each class like this
if __name__ == '__main__':
root = Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.focus_set() # <-- move focus to this widget
root.geometry("%dx%d+0+0" % (w, h))
root.title("Circus ticketing system")
UI_Class = GUI(root)
Program_Class = Program()
root.mainloop()
i set variables in GUI like this:
self.tenAmShowBtn = Button(self.fMain,text='10am Show',command=Program_Class.tenAmShow)
self.tenAmShowBtn.grid(column=0,row=2)
and to access variables in (ex)GUI from Program i do like this:
UI_Class.tenAmShowBtn.config(bg='#00f0ff')
but i keep getting errors like NameError: name 'UI_Class' is not defined
and NameError: name 'Program_Class' is not defined
and AttributeError: 'GUI' object has no attribute 'tenAmShowBtn'i don't understand how the hell do i do this, the Program class continuosly has to access the GUI and edit variables and widgets, but i can't access variables, keep getting error after error, it woks great when i put everything in 1 class, i just CAN'T get this to work with 2 separete classes.
I put the whole code because i cannot explain in just bits of code, i aplogise.
try:
# for Python2
from Tkinter import *
except ImportError:
# for Python3
from tkinter import *
from random import randint
#from user import Program
class GUI:
def __init__(self, parent):
self.seats_being_bought1 = IntVar()#Light-Blue buttons number for textvariable
self.seats_being_bought1.set(0)
self.seats_being_bought2 = IntVar()#Light-Blue buttons number for textvariable
self.seats_being_bought2.set(0)
self.seats_being_bought3 = IntVar()#Light-Blue buttons number for textvariable
self.seats_being_bought3.set(0)
self.available_seats1 = IntVar() #Non-red buttons
self.available_seats1.set("0")
self.available_seats2 = IntVar() #Non-red buttons
self.available_seats2.set(0)
self.available_seats3 = IntVar() #Non-red buttons
self.available_seats3.set(0)
self.pricePerTicket1 = IntVar()
self.pricePerTicket1.set(5)
self.pricePerTicket2 = IntVar()#<> Ticket/Seat Price Variables
self.pricePerTicket2.set(5)
self.pricePerTicket3 = IntVar()
self.pricePerTicket3.set(12)
self.totalPrice1 = IntVar()
self.totalPrice1.set(0)
self.totalPrice2 = IntVar()#total price variables
self.totalPrice2.set(0)
self.totalPrice3 = IntVar()
self.totalPrice3.set(0)
self.totalTicketsSold = IntVar()#Total seats sold
self.totalTicketsSold.set(0)
self.totalIncome = IntVar()#Total income
self.totalIncome.set(0)
self.white = '#ffffff' #save time
self.currentShow = StringVar()#currrent show
self.instructions_text = 'Select the show you desire, then click one of the seats to the right and click the buy button'
self.button_list1={} #all seats(Buttons)as matrix/object
self.button_list2={}
self.button_list3={}
self.total_seats1 = StringVar()
self.total_seats2 = StringVar()
self.total_seats3 = StringVar()
self.total_seats1.set('/250')
self.total_seats2.set('/150')
self.total_seats3.set('/150')
self.selected_button_list1=[] #Light-Blue buttons
self.selected_button_list2=[] #Light-Blue buttons
self.selected_button_list3=[] #Light-Blue buttons
self.previousTransactionButtonList1 = []#List of Seats in the last transaction
self.previousTransactionButtonList2 = []
self.previousTransactionButtonList3 = []
self.automatic_seat_selection_no = IntVar()#automatic seat selection number
self.automatic_seat_selection_no.set(0)
self.f1 = Frame(parent) #Frame for Seats/Buttons
self.seatTitle = Label(self.f1,bg=self.white,textvariable=self.currentShow).grid(row=0,column=0,columnspan=11,sticky=E+W)
self.f1.grid(column=2,row=0)
self.f2 = Frame(parent) #Frame for Seats/Buttons
self.seatTitle = Label(self.f2,bg=self.white,textvariable=self.currentShow).grid(row=0,column=0,columnspan=11,sticky=E+W)
self.f2.grid(column=2,row=0)
self.f3 = Frame(parent) #Frame for Seats/Buttons
self.seatTitle = Label(self.f3,bg=self.white,textvariable=self.currentShow).grid(row=0,column=0,columnspan=11,sticky=E+W)
self.f3.grid(column=2,row=0)
self.f2.grid_remove() #Hide other 2 frames
self.f3.grid_remove() #Hide other 2 frames
#self.create_UI(parent)
#START WITH 10AM SHOW
#self.currentShow.set('10Am Show')
#self.tenAmShowBtn.config(bg='#00f0ff')
Program.tenAmShow(Program)
Program.displaySeats(10)#10 refers to 10am show
#CREATING OTHER SEATS BUT THEIR FRAMES ARE HIDDEN
Program.displaySeats(3)
Program.displaySeats(8)
def create_UI(self,parent):
self.fMain = Frame(parent)#Frame for rest of program
fLegend = Frame(self.fMain)#Frame for Legend
legendLabel = Label(fLegend,text='Legend').grid(column=0,row=0,columnspan=3,sticky=E+W)
legendRed = Label(fLegend,text='seat123',fg='#ff0000',bg='#ff0000').grid(column=0,row=1,sticky=E+W)
legendRed1 = Label(fLegend,text=' =').grid(column=1,row=1)
legendRed2 = Label(fLegend,text='Taken Seat').grid(column=2,row=1)
legendLightRed = Label(fLegend,text='seat123',fg='#f99999',bg='#f99999').grid(column=0,row=2,sticky=E+W)
legendLightRed1 = Label(fLegend,text=' =').grid(column=1,row=2)
legendLightRed2 = Label(fLegend,text='Bought Seat').grid(column=2,row=2)
legendLightBlue = Label(fLegend,text='seat123',fg='#00f0ff',bg='#00f0ff').grid(column=0,row=3,sticky=E+W)
legendLightBlue1 = Label(fLegend,text=' =').grid(column=1,row=3)
legendLightBlue2 = Label(fLegend,text='Selected Seat').grid(column=2,row=3)
fLegend.grid(column=0,row=0,columnspan=3)
#end Legend frame
self.instructions = Label(self.fMain, text=self.instructions_text).grid(column=0,row=1,columnspan=3)
#Show Selection gui
self.tenAmShowBtn = Button(self.fMain,text='10am Show',command=Program_Class.tenAmShow)
self.tenAmShowBtn.grid(column=0,row=2)
self.threePmShowBtn = Button(self.fMain,text='3pm Show',command=Program_Class.threePmShow)
self.threePmShowBtn.grid(column=1,row=2)
self.eightPmShowBtn = Button(self.fMain,text='8Pm Show',command=Program_Class.eightPmShow)
self.eightPmShowBtn.grid(column=2,row=2)
#Purchase details and commands gui
self.seat_amountLabel = Label(self.fMain, text='Amount of seats Available').grid(column=0, row=3)
self.seat_amountEntry = Label(self.fMain, textvariable=self.available_seats1,bg="#444444",fg='#ffffff',anchor=E)
self.seat_amountEntry.grid(column=1,row=3,sticky=E+W)
self.seat_amountTotal = Label(self.fMain,textvariable=self.total_seats1 ,bg='#444444',fg='#ffffff',anchor=W)
self.seat_amountTotal.grid(column=2,row=3,sticky=E+W)
self.seatsBeingBoughtLabel = Label(self.fMain,text='Amount of seats being purchased').grid(column=0,row=4)
self.seatsBeingBoughtVal = Label(self.fMain, textvariable=self.seats_being_bought1,bg="#444444",fg='#ffffff')
self.seatsBeingBoughtVal.grid(column=1,row=4,columnspan=2,sticky=E+W)
#price per ticket
self.pricePerTicketLabel = Label(self.fMain,text='Cost per Ticket/Seat in $').grid(column=0,row=5)
self.pricePerTicketVal = Label(self.fMain,textvariable=self.pricePerTicket1,bg='#ffffff',fg='#444444')
self.pricePerTicketVal.grid(column=1,row=5,columnspan=2,sticky=E+W)
#total price
self.totalPriceLabel = Label(self.fMain,text='Total Price in $').grid(column=0,row=6)
self.totalPriceVal = Label(self.fMain,textvariable=self.totalPrice1,bg='#ffffff',fg='#444444')
self.totalPriceVal.grid(column=1,row=6,columnspan=2,sticky=E+W)
#Automatically select seats
self.auto_seat_selection_label = Label(self.fMain,text='Amount of seats to buy:').grid(column=0,row=7)
self.auto_seat_selection_entry = Entry(self.fMain, textvariable=self.automatic_seat_selection_no).grid(column=1,row=7,columnspan=2,sticky=E+W)
#cancel and purchase button
self.resetBtn = Button(self.fMain,text="Cancel/Reset",bg='#ff0000',command=Program_Class.CancelTransaction).grid(column=0,row=8,columnspan=1,sticky=E+W)
self.buyTicketsBtn = Button(self.fMain,text="Buy ticket",bg='#00f0ff',command=Program_Class.click_function).grid(column=1,row=8,columnspan=2,sticky=E+W)
#totals
self.totalTicketsSoldLabel = Label(self.fMain,text='Total tickets sold:').grid(column=0,row=9)
self.totalTicketsSoldVal = Label(self.fMain,textvariable=self.totalTicketsSold).grid(column=1,row=9,columnspan=2)
self.totalIncomeLabel = Label(self.fMain,text='Total Income for the Day in $:').grid(column=0,row=10)
self.totalIncomeVal = Label(self.fMain,textvariable=self.totalIncome).grid(column=1,row=10,columnspan=2)
self.fMain.grid(column=1,row=0,sticky=N)
class Program:
def __init__(self):
print('test')
def click_function(self): #Buy Button click
show = self.currentShow.get()
action = 0
inputed_seat = self.automatic_seat_selection_no.get()
#for automatic seat selection
if(inputed_seat != 0):
if(show == '10Am Show'):
button_list = self.button_list1
available_seats = self.available_seats1.get()
elif(show == '3Pm Show'):
button_list = self.button_list2
available_seats = self.available_seats2.get()
else:
button_list = self.button_list3
available_seats = self.available_seats3.get()
counter_var = 1
seat = 1
while counter_var <= inputed_seat:#i use while loop instead of for loop so i can continue/extend the loop if i find a taken/red seat
if(inputed_seat > available_seats):
print('Not enough seats available')
break
else:
if seat in button_list:
if(button_list[seat]['bg'] != '#f99999' and button_list[seat]['bg'] != '#00f0ff'):
self.SeatClick(seat)
else:
counter_var -= 1
else:#seat is taken/red
if(available_seats == 0):
print('Not enough seats available')
break
else:
counter_var -= 1
counter_var += 1
seat += 1
self.automatic_seat_selection_no.set(0)
self.click_function()
else:#for manual seat selection
if(show == '10Am Show'):
action = len(self.selected_button_list1)
elif(show == '3Pm Show'):
action = len(self.selected_button_list2)
else:
action = len(self.selected_button_list3)
if(action != 0):
if(show == '10Am Show'):
del self.previousTransactionButtonList1[:]#Clear last transaction
for i in range(len(self.selected_button_list1)):
self.button_list1[self.selected_button_list1[i]].config(bg='#f99999')
self.available_seats1.set(self.available_seats1.get() - 1)
#save to previous transactions
self.previousTransactionButtonList1.append(self.button_list1[self.selected_button_list1[i]])
self.selected_button_list1 = []
self.seats_being_bought1.set(0)
self.totalPrice1.set(0)
elif(show == '3Pm Show'):
del self.previousTransactionButtonList2[:]#Clear last transaction
for i in range(len(self.selected_button_list2)):
self.button_list2[self.selected_button_list2[i]].config(bg='#f99999')
self.available_seats2.set(self.available_seats2.get() - 1)
#save to previous transactions
self.previousTransactionButtonList2.append(self.button_list2[self.selected_button_list2[i]])
self.selected_button_list2 = []
self.seats_being_bought2.set(0)
self.totalPrice2.set(0)
else:
del self.previousTransactionButtonList3[:]#Clear last transaction
for i in range(len(self.selected_button_list3)):
self.button_list3[self.selected_button_list3[i]].config(bg='#f99999')
self.available_seats3.set(self.available_seats3.get() - 1)
#save to previous transactions
self.previousTransactionButtonList3.append(self.button_list3[self.selected_button_list3[i]])
self.selected_button_list3 = []
self.seats_being_bought3.set(0)
self.totalPrice3.set(0)
#get total seats sold INITIAL ONLY, SPECIFIC FUNCTION AT END OF PROGRAM
self.resetVal()
else:
print('No Seats Selected!')
def CancelTransaction(self):
show = self.currentShow.get()
if(show == '10Am Show' and len(self.previousTransactionButtonList1) >= 1):
for x in range(len(self.previousTransactionButtonList1)):
self.previousTransactionButtonList1[x].config(bg='SystemButtonFace')#make button return to available color
self.available_seats1.set(self.available_seats1.get() + 1)#Adjust available seat counter
self.totalTicketsSold.set(self.totalTicketsSold.get() - 1)
self.resetVal()
del self.previousTransactionButtonList1[:]#delete/clear previous transaction
elif(show == '3Pm Show' and len(self.previousTransactionButtonList2) >= 1):
for x in range(len(self.previousTransactionButtonList2)):
self.previousTransactionButtonList2[x].config(bg='SystemButtonFace')
self.available_seats2.set(self.available_seats2.get() + 1)#Adjust available seat counter
self.totalTicketsSold.set(self.totalTicketsSold.get() - 1)
self.resetVal()
del self.previousTransactionButtonList2[:]#delete/clear previous transaction
elif(show == '8Pm Show' and len(self.previousTransactionButtonList3) >= 1):
for x in range(len(self.previousTransactionButtonList3)):
self.previousTransactionButtonList3[x].config(bg='SystemButtonFace')
self.available_seats3.set(self.available_seats3.get() + 1)#Adjust available seat counter
self.totalTicketsSold.set(self.totalTicketsSold.get() - 1)
self.resetVal()
del self.previousTransactionButtonList3[:]#delete/clear previous transaction
else:
print('no previous transaction found')
def seatCounter(self,taken,show): #to count available seats
if(show == 1):
self.available_seats1.set(self.available_seats1.get() - taken)
elif(show == 2):
self.available_seats2.set(self.available_seats2.get() - taken)
else:
self.available_seats3.set(self.available_seats3.get() - taken)
#just to initially update the variables
def resetVal(self):
ticketSold1 = 250 - self.available_seats1.get()
ticketSold2 = 150 - self.available_seats2.get()
ticketSold3 = 150 - self.available_seats3.get()
self.totalTicketsSold.set(ticketSold1 + ticketSold2 + ticketSold3)
self.totalIncome.set((ticketSold1 * 5) + (ticketSold2 * 5) + (ticketSold3 * 12))
#CLICK ON SEAT/BUTTON
def SeatClick(self,seat_no):
show = self.currentShow.get()
action = 0
if(show == '10Am Show'):
action = self.button_list1[seat_no]['bg']
elif(show == '3Pm Show'):
action = self.button_list2[seat_no]['bg']
elif(show == '8Pm Show'):
action = self.button_list3[seat_no]['bg']
else:
return False
if(action == '#f99999'):
print('already bought')
else:
if(show == '10Am Show'):
if(seat_no in self.selected_button_list1):#IF Seat/Button already selected, then remove .after(1000, self.update_clock)
self.button_list1[seat_no].config(bg='SystemButtonFace')
self.selected_button_list1.remove(seat_no)
self.seats_being_bought1.set(str(len(self.selected_button_list1)))
self.totalPrice1.set(self.pricePerTicket1.get() * len(self.selected_button_list1))
else:
self.button_list1[seat_no].config(bg='#00f0ff')#IF Seat/Button not selected then toggle it
self.selected_button_list1.append(seat_no)
self.seats_being_bought1.set(str(len(self.selected_button_list1)))
self.totalPrice1.set(self.pricePerTicket1.get() * len(self.selected_button_list1))
elif(show == '3Pm Show'):
if(seat_no in self.selected_button_list2):
self.button_list2[seat_no].config(bg='SystemButtonFace')#IF Seat/Button already selected, then remove
self.selected_button_list2.remove(seat_no)
self.seats_being_bought2.set(str(len(self.selected_button_list2)))
self.totalPrice2.set(self.pricePerTicket2.get() * len(self.selected_button_list2))
else:
self.button_list2[seat_no].config(bg='#00f0ff')#IF Seat/Button not selected then toggle it
self.selected_button_list2.append(seat_no)
self.seats_being_bought2.set(len(self.selected_button_list2))
self.totalPrice2.set(self.pricePerTicket2.get() * len(self.selected_button_list2))
else:
if(seat_no in self.selected_button_list3):
self.button_list3[seat_no].config(bg='SystemButtonFace')#IF Seat/Button already selected, then remove
self.selected_button_list3.remove(seat_no)
self.seats_being_bought3.set(str(len(self.selected_button_list3)))
self.totalPrice3.set(self.pricePerTicket3.get() * len(self.selected_button_list3))
else:
self.button_list3[seat_no].config(bg='#00f0ff')#IF Seat/Button not selected then toggle it 613553
self.selected_button_list3.append(seat_no)
self.seats_being_bought3.set(len(self.selected_button_list3))
self.totalPrice3.set(self.pricePerTicket3.get() * len(self.selected_button_list3))
# SHOW SELECTION
def tenAmShow(self):
UI_Class.tenAmShowBtn.config(bg='#00f0ff')
self.threePmShowBtn.config(bg=self.white)
self.eightPmShowBtn.config(bg=self.white)
self.currentShow.set('10Am Show')
self.seat_amountEntry.config(textvariable = self.available_seats1)
self.seatsBeingBoughtVal.config(textvariable=self.seats_being_bought1)
self.pricePerTicketVal.config(textvariable=self.pricePerTicket1)
self.totalPriceVal.config(textvariable=self.totalPrice1)
self.seat_amountTotal.config(textvariable=self.total_seats1)
self.f1.grid()
self.f2.grid_remove()
self.f3.grid_remove()
def threePmShow(self):
self.threePmShowBtn.config(bg='#00f0ff')
self.tenAmShowBtn.config(bg=self.white)
self.eightPmShowBtn.config(bg=self.white)
self.currentShow.set('3Pm Show')
self.seat_amountEntry.config(textvariable = self.available_seats2)
self.seatsBeingBoughtVal.config(textvariable=self.seats_being_bought2)
self.pricePerTicketVal.config(textvariable=self.pricePerTicket2)
self.totalPriceVal.config(textvariable=self.totalPrice2)
self.seat_amountTotal.config(textvariable=self.total_seats2)
self.f1.grid_remove()
self.f2.grid()
self.f3.grid_remove()
def eightPmShow(self):
self.eightPmShowBtn.config(bg='#00f0ff')
self.tenAmShowBtn.config(bg=self.white)
self.threePmShowBtn.config(bg=self.white)
self.currentShow.set('8Pm Show')
self.seat_amountEntry.config(textvariable = self.available_seats3)
self.seatsBeingBoughtVal.config(textvariable= self.seats_being_bought3)
self.pricePerTicketVal.config(textvariable=self.pricePerTicket3)
self.totalPriceVal.config(textvariable=self.totalPrice3)
self.seat_amountTotal.config(textvariable=self.total_seats3)
self.f1.grid_remove()
self.f2.grid_remove()
self.f3.grid()
#BUTTON/SEAT CREATION AND DISPLAY
def createSeats(self,num_of_seats,frame_pointer):
col = num_of_seats / 10
if(frame_pointer == 1):
seat_counter1 = 1
for x in range(int(col)):
X = x + 10
for y in range(1, 11):
taken_seats = randint(1,3)
if(taken_seats == 3):
b1 = Button(
self.f1, text='Seat%d' % seat_counter1,
name='seat%d' % seat_counter1, bg='#ff0000'
)
b1.grid(row=X, column=y)
seat_counter1 += 1
self.seatCounter(1, 1)
else:
b1 = Button(
self.f1, text='Seat%d' % seat_counter1,
name='seat%d' % seat_counter1,command= lambda j = seat_counter1: self.SeatClick(j)
)
b1.grid(row=X, column=y)
self.button_list1[seat_counter1] = b1
seat_counter1 += 1
elif(frame_pointer == 2):
seat_counter2 = 1
for x in range(int(col)):
X = x + 10
for y in range(1, 11):
taken_seats = randint(1,3)
if(taken_seats == 3):
b2 = Button(
self.f2, text='Seat%d' % seat_counter2,
name='seat%d' % seat_counter2, bg='#ff0000'
)
b2.grid(row=X, column=y)
seat_counter2 += 1
self.seatCounter(1, 2)
else:
b2 = Button(
self.f2, text='Seat%d' % seat_counter2,
name='seat%d' % seat_counter2,command= lambda j = seat_counter2: self.SeatClick(j)
)
b2.grid(row=X, column=y)
self.button_list2[seat_counter2] = b2
seat_counter2 += 1
else:
seat_counter3 = 1
for x in range(int(col)):
X = x + 10
for y in range(1, 11):
taken_seats = randint(1,3)
if(taken_seats == 3):
b3 = Button(
self.f3, text='Seat%d' % seat_counter3,
name='seat%d' % seat_counter3, bg='#ff0000'
)
b3.grid(row=X, column=y)
seat_counter3 += 1
self.seatCounter(1, 3)
else:
b3 = Button(
self.f3, text='Seat%d' % seat_counter3,
name='seat%d' % seat_counter3,command= lambda j = seat_counter3: self.SeatClick(j)
)
b3.grid(row=X, column=y)
self.button_list3[seat_counter3] = b3
seat_counter3 += 1
def displaySeats(self,show):
if(show == 10):
self.available_seats1.set(250)
self.createSeats(250, 1)
elif(show == 3):
self.available_seats2.set(150)
self.createSeats(150, 2)
else:
self.available_seats3.set(150)
self.createSeats(150, 3)
self.resetVal()
if __name__ == '__main__':
root = Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
#root.overrideredirect(1) #removes menubar
root.focus_set() # <-- move focus to this widget
root.geometry("%dx%d+0+0" % (w, h))
root.title("Circus ticketing system")
UI_Class = GUI(root)
Program_Class = Program()
root.mainloop()
the Program_Class object is instantiated after the UI_Class object and the latter doesn't reference the prior. Try passing Program_Class to the GUI constructor:
Program_Class = Program()
UI_Class = GUI(root, Program_Class)
where:
class GUI:
def __init__(self, parent, program):
self.program = program
then you should be able to reference self.program.

Categories