我有2个类,我就像这样创建每个类的实例
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()
我在GUI中设置变量如下:
self.tenAmShowBtn = Button(self.fMain,text='10am Show',command=Program_Class.tenAmShow)
self.tenAmShowBtn.grid(column=0,row=2)
并且从程序i中访问(ex)GUI中的变量是这样的:
UI_Class.tenAmShowBtn.config(bg='#00f0ff')
但我一直收到NameError: name 'UI_Class' is not defined
等错误
和NameError: name 'Program_Class' is not defined
和AttributeError: 'GUI' object has no attribute 'tenAmShowBtn'
我不明白我到底怎么做,程序类连续不得不访问GUI并编辑变量和小部件,但我无法访问变量,错误后不断收到错误,它开始工作很棒,当我把所有东西都放在一个班级时,我只是不能用2个separete类来工作。
我把整个代码放在一边,因为我无法用一些代码来解释,我是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()
答案 0 :(得分:1)
Program_Class
对象在UI_Class
对象之后被实例化,而后者没有引用先前的对象。尝试将Program_Class
传递给GUI
构造函数:
Program_Class = Program()
UI_Class = GUI(root, Program_Class)
其中:
class GUI:
def __init__(self, parent, program):
self.program = program
然后你应该能够引用self.program
。