This code is part of a program I'm developing. It uses CSV to read from a file. This part of the code is supposed to compare the input date to the dates in the CSV file and output any matching dates and the information they carry. This is the CSV data: CSV file
The problem is, when I input another date in the filed, I want it to delete any labels created in the for loop of the code. The deleteResults function only deletes the last set of labels created. Is there a way to delete via another function all the labels created in the for loop, not mattering the amount of labels created with the for loop? Thanks.
#PLANNER
from tkinter import *
import tkinter
from csv import*
import csv
colW=['#000000','#f9f4bd','#fff200','black','#2378c8','#ed1c24']
colSch=colW
accessDayPage=False
results=False
existingEvents=[]
eventsFile=open("dayFile.csv","r+")
evImport=csv.reader(eventsFile)
for row in evImport:
existingEvents.append(row)
def deleteResults():
global dateLabel,descriptionLabel,titleLabel,results
if results==True:
dateLabel.destroy()
descriptionLabel.destroy()
titleLabel.destroy()
evTypeLabel.destroy()
results=False
def destroyaccessDay():
global accessDayPage
if accessDayPage==True:
accessD.destroy()
accessM.destroy()
accessY.destroy()
slash.destroy()
slash1.destroy()
accessButton.destroy()
accessDayPage=False
def go():
global dayAcc,existingEvents,dateLabel,descriptionLabel,titleLabel,dayAccFORSEARCH,eventsCreated,evTypeLabel,results
deleteResults()
lineforevent=93
leDay="0"
leMon="404"
if accessD.get()=="01":
leDay="1"
elif accessD.get()=="02":
leDay="2"
elif accessD.get()=="03":
leDay="3"
elif accessD.get()=="04":
leDay="4"
elif accessD.get()=="05":
leDay="5"
elif accessD.get()=="06":
leDay="6"
elif accessD.get()=="07":
leDay="7"
elif accessD.get()=="08":
leDay="8"
elif accessD.get()=="09":
leDay="9"
elif accessD.get()=="1":
leDay="1"
elif accessD.get()=="2":
leDay="2"
elif accessD.get()=="3":
leDay="3"
elif accessD.get()=="4":
leDay="4"
elif accessD.get()=="5":
leDay="5"
elif accessD.get()=="6":
leDay="6"
elif accessD.get()=="7":
leDay="7"
elif accessD.get()=="8":
leDay="8"
elif accessD.get()=="9":
leDay="9"
elif accessD.get()=="10":
leDay="10"
elif accessD.get()=="11":
leDay="11"
elif accessD.get()=="12":
leDay="12"
elif accessD.get()=="13":
leDay="13"
elif accessD.get()=="14":
leDay="14"
elif accessD.get()=="15":
leDay="15"
elif accessD.get()=="16":
leDay="16"
elif accessD.get()=="17":
leDay="17"
elif accessD.get()=="18":
leDay="18"
elif accessD.get()=="19":
leDay="19"
elif accessD.get()=="20":
leDay="20"
elif accessD.get()=="21":
leDay="21"
elif accessD.get()=="22":
leDay="22"
elif accessD.get()=="23":
leDay="23"
elif accessD.get()=="24":
leDay="24"
elif accessD.get()=="25":
leDay="25"
elif accessD.get()=="26":
leDay="26"
elif accessD.get()=="27":
leDay="27"
elif accessD.get()=="28":
leDay="28"
elif accessD.get()=="29":
leDay="29"
elif accessD.get()=="30":
leDay="30"
elif accessD.get()=="31":
leDay="31"
if accessM.get()=="1":
leMon="January"
elif accessM.get()=="01":
leMon="January"
elif accessM.get()=="2":
leMon="February"
elif accessM.get()=="02":
leMon="February"
elif accessM.get()=="3":
leMon="March"
elif accessM.get()=="03":
leMon="March"
elif accessM.get()=="4":
leMon="April"
elif accessM.get()=="04":
leMon="April"
elif accessM.get()=="5":
leMon="May"
elif accessM.get()=="05":
leMon="May"
elif accessM.get()=="6":
leMon="June"
elif accessM.get()=="06":
leMon="June"
elif accessM.get()=="7":
leMon="July"
elif accessM.get()=="07":
leMon="July"
elif accessM.get()=="8":
leMon="August"
elif accessM.get()=="08":
leMon="August"
elif accessM.get()=="9":
leMon="September"
elif accessM.get()=="09":
leMon="September"
elif accessM.get()=="10":
leMon="October"
elif accessM.get()=="10":
leMon="October"
elif accessM.get()=="11":
leMon="November"
elif accessM.get()=="11":
leMon="November"
elif accessM.get()=="12":
leMon="December"
elif accessM.get()=="12":
leMon="December"
dayAcc=str(leDay+leMon+accessY.get())
dayAccFORSEARCH=str(dayAcc+"'")
for i in existingEvents:
global results
if i[0]==dayAccFORSEARCH:
deleteResults()
titleLabel=tkinter.Label(main, text=i[1],fg=colSch[3],bg=colSch[1],font=("DFKai-SB",9,"bold"))
titleLabel.place(x=140,y=lineforevent)
evTypeLabel=tkinter.Label(main, text=i[2],fg=colSch[4],bg=colSch[0],font=("Consolas",9))
evTypeLabel.place(x=320,y=lineforevent)
descriptionLabel=tkinter.Label(main,text=i[3],fg=colSch[5],bg=colSch[1],font=("Garamond",9))
descriptionLabel.place(x=420,y=lineforevent)
lineforevent+=35
dateLabel=tkinter.Label(main, text=dayAcc,fg=colSch[4],bg=colSch[0],font=("Consolas",12))
dateLabel.place(x=140,y=35)
results=True
def accessDay():
destroyaccessDay()
deleteResults()
global accessD,accessM,accessY,slash,slash1,accessButton,accessDayPage
accessD=tkinter.Entry(main,width=2)
accessD.place(x=140, y=8)
slash=tkinter.Label(main,text="/",fg=colSch[4],bg=colSch[0],font=("14"))
slash.place(x=160,y=8)
accessM=tkinter.Entry(main,width=2)
accessM.place(x=175, y=8)
slash1=tkinter.Label(main,text="/",fg=colSch[4],bg=colSch[0],font=("14"))
slash1.place(x=195,y=8)
accessY=tkinter.Entry(main,width=4)
accessY.place(x=210, y=8)
accessButton=tkinter.Button(main, text="Go",bg=colSch[2],fg=colSch[4],width=6,height=1, font=("Copperplate Gothic Light","9"),command=go)##
accessButton.place(x=245,y=8)
accessDayPage=True
main=tkinter.Tk()
main.configure(bg=colSch[0])
main.geometry('780x375')
w=Canvas(main,width=780,height=375)
w.pack()
rect1=w.create_rectangle(0,0,775,375,fill=colSch[0])
rect2=w.create_rectangle(0,0,120,375,fill=colSch[1])
accessDay=tkinter.Button(main,text="Access Day",bg=colSch[2],fg=colSch[4],width=15,height=3,relief=FLAT, font=("Bernard MT Condensed","11"),command=accessDay)
accessDay.place(x=5,y=5)
main.mainloop()
You'll find that the method is similar to this post here where the example I gave uses dynamicly generated widgets. You'll want to look at .destoy() instead of .configure()
Side notes:
I would suggest use in for your if statements to shorten the code since you are performing the same operation for a different instance.
if accessM.get() in {"1", "01"}:
leMon="January"
Alternatively as Bryan Oakley suggested. Using a dictionary. I believe it would be something like this.
date_values = {"01" : ("January", range(1, 31)),
"02" : ("February", range(1, 30)), # Check for leap years
.....}
leMon = date_values[accessM.get()][0]
d = int(accessD.get())
# Checks if day is in month range
leDay = str(d) if d in date_values[accessM.get()][1] else None
Related
so my code is designed to basically create a bingo card, then when you press enter draws a number and changes the bingo card value to 0 if the drawn number matches. My issue is that my code isn't properly producing a bingo or not a bingo which you can see towards the end of the code. How should I change this so that my code will return bingo when I have bingo.
import random #Condernsed solo version with call and player together
import numpy as np
def bingo_card(): #Code to generate BINGO card using numpy array
test1=np.array(random.sample(range(1,16),5))
test2=np.array(random.sample(range(16,31),5))
test3=np.array(random.sample(range(31,46),5))
test4=np.array(random.sample(range(46,61),5))
test5=np.array(random.sample(range(61,76),5))
test= np.concatenate((test1,test2,test3,test4,test5))
test= test.reshape(5,5)
test[2,2]=0
bingo_card.test = test
BINGO= print("Your Card")
print("B", test[0]),
print("I", test[1]),
print("N", test[2]),
print("G", test[3]),
print("O", test[4])
card = BINGO
return card
def called_value(): #should be close to the code we use to check if called value is in generated matrix, may need some formatting and fixing
checked_card = bingo_card.test
while True:
called_num = input ("Type called number to mark card or press 's' to quit if you think you have bingo").lower()
if called_num != "s":
number_check = int(called_num)
checked_card = np.where(checked_card==number_check,0,checked_card)
BINGO = print("Your Card")
print("B", checked_card[0]),
print("I", checked_card[1]),
print("N", checked_card[2]),
print("G", checked_card[3]),
print("O", checked_card[4])
elif called_num == "s":
BINGO = print("Your Card")
print("B", checked_card[0]),
print("I", checked_card[1]),
print("N", checked_card[2]),
print("G", checked_card[3]),
print("O", checked_card[4])
row_zeros = np.count_nonzero(checked_card == 0, axis=1)
col_zeros = np.count_nonzero(checked_card == 0, axis=0)
diagonal_zeros = np.count_nonzero(np.diag(checked_card) == 0)
diagonal1_zeros = np.count_nonzero(np.diag(np.fliplr(checked_card)) == 0)
for i in range (5):
if (row_zeros[i] or col_zeros[i]) == 5:
return ("Bingo!")
elif (diagonal_zeros or diagonal1_zeros) == 5:
return ("Bingo!")
else:
return ("Not Bingo")
def solo():
bingo_card()
called_value()
solo()
You've committed one of the classic blunders.
for i in range (5):
if (row_zeros[i] or col_zeros[i]) == 5:
return ("Bingo!")
elif (diagonal_zeros or diagonal1_zeros) == 5:
return ("Bingo!")
else:
return ("Not Bingo")
row_zeros[i] or col_zeros[i] is going to be True or False (usually True), which is never equal to 5. And you don't need to loop to check the diagonals. You need:
if diagonal_zeros == 5 or diagonal1_zeros == 5:
return ("Bingo!")
for i in range (5):
if row_zeros[i] == 5 or col_zeros[i] == 5:
return ("Bingo!")
return ("Not Bingo")
I am quite new with programming in general and I have a project that I need to write a status of ~50 chips onto an RFID. To begin with I used a loop to create ~50 option menus for the Chip statuses and right now I am having trouble appending the selected options from all the option menus onto a list. All its giving me is the selected option from the very last option menu and I am not quite sure what to do about it.
Any help is appreciated
Here is the code I have so far"
from tkinter import *
clear = lambda: os.system('cls')
clear()
def get_wafer():
global waferNum
result = simpledialog.askstring("Wafer Number", "Enter Wafer Number Here:")
waferNum = result
def get_chips():
global chips_list
chips= selected.get()
if chips == 'P':
chips = '0'
elif chips=='L' :
chips='1'
elif chips=='R' :
chips='2'
elif chips=='F' :
chips='3'
elif chips=='X':
chips='4'
elif chips=='O' :
chips='5'
elif chips=='/':
chips='6'
elif chips=='M' :
chips='7'
elif chips=='B' :
chips='8'
elif chips=='LO':
chips='9'
elif chips=='L/' :
chips='a'
elif chips=='LB' :
chips='b'
elif chips=='N':
chips='c'
elif chips=='S' :
chips='d'
elif chips=='NF' :
chips='e'
elif chips=='V':
chips='f'
else:
chips=''
chips_list=[]
chips_list.append(chips)
root= Tk()
root.title("Chips and Wafer")
root.geometry("850x450")
z=1
for x in range(8):
i = 0
y = 0
while i < 12 and y < 12:
status_opt=['P','L','R','F','X','O','/','M','B','LO','L/','LB','N','S','NF','V']
selected = StringVar(root)
selected.set("Status")
label_0=Label(root, text = "Chip #"+ str(z))
label_0.grid(row=y,column=x+1,pady=5,padx=5)
my_entry= OptionMenu(root,selected, *status_opt)
my_entry.grid(row=i+1,column=x+1,pady=5,padx=5)
i = i+2
y = y+2
z = z+1
waferButton = Button(root, text="Enter Wafer Number",command = lambda:[get_wafer(),get_chips()],width = 16,height=1)
waferButton.grid(row=0,column=0,pady=5,padx=5)
saveButton = Button(root, text="Save",command = root.destroy,width = 16,height=1)
saveButton.grid(row=1,column=0,pady=5,padx=5)
root.mainloop()
print (waferNum)
print (chips_list)
So ive been writing Python for a bit now. I've decided to make an app to help my sister with multiplication tables. Im writing the code that will randomly pick from my 10 lists of the diffrent questions (I know there are better ways to write it but it gave me abilities i wanted to use with SQL). lists are by Table (Tone,Ttwo,Tthree, etc.) inside Tone would be ['1*1','1*2',...] then as seen in the if statement it calls by calling the list and problem with randomly generated numbers.
def pick_question():
Table = random.randint(0,9)
Col = random.randint(0,9)
if Table == 0:
if Col == 0:
return Tone[0]
elif Col == 1:
return Tone[1]
elif Col == 2:
return Tone[2]
elif Col == 3:
return Tone[3]
elif Col == 4:
return Tone[4]
elif Col == 5:
return Tone[5]
elif Col == 6:
return Tone[6]
elif Col == 7:
return Tone[7]
elif Col == 8:
return Tone[8]
elif Col == 9:
return Tone[9]
elif Table == 1:
if Col == 0:
return Ttwo[0]
elif Col == 1:
return Ttwo[1]
elif Col == 2:
return Ttwo[2]
elif Col == 3:
return Ttwo[3]
elif Col == 4:
return Ttwo[4]
elif Col == 5:
return Ttwo[5]
elif Col == 6:
return Ttwo[6]
elif Col == 7:
return Ttwo[7]
elif Col == 8:
return Ttwo[8]
elif Col == 9:
return Ttwo[9]
obviously it would keep going but it was already quite long. was wondering if there was anyway to make this not hae to be so repetitive and look better...
def pick_question():
Table = random.randint(0,9)
Col = random.randint(0,9)
return [Tone,Ttwo][Table][Col]
I guess what you are trying to write is
import random
Tone = [f"1*{i}" for i in range(1,10)]
Ttwo = [f"2*{i}" for i in range(1,10)]
Tthree = [f"3*{i}" for i in range(1,10)]
Tfour = [f"4*{i}" for i in range(1,10)]
Tfive = [f"5*{i}" for i in range(1,10)]
Tsix = [f"6*{i}" for i in range(1,10)]
Tseven = [f"7*{i}" for i in range(1,10)]
Teight = [f"8*{i}" for i in range(1,10)]
Tnine = [f"9*{i}" for i in range(1,10)]
Questions = [
Tone,
Ttwo,
Tthree,
Tfour,
Tfive,
Tsix,
Tseven,
Teight,
Tnine,
]
def pick_question():
Table = random.randint(0,8)
Col = random.randint(0,8)
return Questions[Table][Col]
print(pick_question())
but I guess what you are trying to do is this:
import random
A=random.randint(1,9)
B=random.randint(1,9)
print(f"{A}*{B}=?")
C=input()
try:
assert A*B==int(C)
print("You are RIGHT!")
except:
print(f"Your are WRONG, right answer is: {A*B}")
Good luck with python! it's an amazing language! :)
Just use a one-dimensional list:
def pick_question():
Table = random.randint(0,9)
Col = random.randint(0,9)
if Table == 0:
return Tone[Col]
elif Table == 1:
return Ttwo[Col]
This will do the trick.
Or even better, a two-dimensional list:
def pick_question():
Table = random.randint(0,9)
Col = random.randint(0,9)
List = [Tone, Ttwo]
return List[Table][Col]
I quite like this solution with dictionaries and the get method:
route = input()
branch = {'y': code1, 'n': code2}.get(route)
This shortens your code and will be easier to read.
Rather than write the inner if structures, why not just
return Tone[Col]
?
In fact, you can create a list with the Tone, Ttwo, etc. inside it and then write
return outer_list[Table][Col]
def pick_question(list_with_tone_ttwo):
table = random.randint(0,9)
col = random.randint(0,9)
return list_with_tone_ttwo[table][col]
EDIT: added full function
I made a game using the terminal and pythons curses module. I steer the snake using the kbinput function. This works great for the number pad and the standard letters, however, when I try to use the direction keys it throws the exception _cureses_error: no input If I hold the keys down eventually one of the commands will get through eventually. I have it in full blocking mode, so it makes no sense to get the no input exception.
I tried a quick test to see if having it running in a thread was a problem, but in my test case the direction keys work fine.
relevant functions are below:
def game():
screen=curses.initscr()
curses.start_color()
curses.raw()
curses.cbreak()
curses.noecho()
screen.keypad(True)
try:
gtime=time.time()
b=Board(screen)
s=Snake(b)
#thread.start_new_thread(steps,(s,b))
thread.start_new_thread(kbinput,(s,b,screen))
....
def kbinput(snake,b,screen):
while snake.alive==True:
key=""
key=screen.getkey()
b.key=key
if key=="q":
snake.alive=False
break
elif (key == "8" or key == "i" or key == 'KEY_UP') and snake.direction != 3: snake.direction=1
elif (key == "6" or key == "l" or key == 'KEY_RIGHT') and snake.direction != 4: snake.direction=2
elif (key == "4" or key == "j" or key == 'KEY_LEFT') and snake.direction != 2: snake.direction=4
elif (key == "5" or key == "k" or key == 'KEY_DOWN') and snake.direction != 1: snake.direction=3
return
EDIT:
Thomas was correct that the problem seems to be with threading the kbinput. To fix the problem I made these changes to the functions:
def game():
screen=curses.initscr()
curses.start_color()
curses.raw()
curses.cbreak()
curses.noecho()
screen.keypad(True)
curses.halfdelay(1)
curses.init_pair(1,curses.COLOR_RED,curses.COLOR_BLACK)
curses.init_pair(2,curses.COLOR_GREEN,curses.COLOR_BLACK)
try:
gtime=time.time()
b=Board(screen)
s=Snake(b)
#thread.start_new_thread(kbinput,(s,b,screen))
while s.alive and s.x != 0 and s.x != b.width-1 and s.y !=1 and s.y != b.height-2:
kbinput(s,b,screen)
gtime=time.time()
update(s,b,screen)
if snake_check(s) == True: break
def kbinput(snake,b,screen):
#while snake.alive==True:
key=""
key2=screen.getch()
if key2==-1: return
try:key=chr(key2)
except:pass
if key=="q":
snake.alive=False
#break
elif (key == "8" or key == "i" or key2 == curses.KEY_UP) and snake.direction != 3: snake.direction=1
elif (key == "6" or key == "l" or key2 == curses.KEY_RIGHT) and snake.direction != 4: snake.direction=2
elif (key == "4" or key == "j" or key2 == curses.KEY_LEFT) and snake.direction != 2: snake.direction=4
elif (key == "5" or key == "k" or key2 == curses.KEY_DOWN) and snake.direction != 1: snake.direction=3
return
Rather than look for a string-literal
key == 'KEY_UP')
look for the defined-constant
key == curses.KEY_UP)
although as noted in a comment, that requires the getch method.
However, this line indicates a more serious problem:
thread.start_new_thread(kbinput,(s,b,screen))
Curses in general is not thread-safe (and python's curses-binding is subject to that limitation):
Why does (fill in the blank) happen when I use two threads?
Hey everyone im new here and im trying to make a game called HiQ now i got the board drawn and everything and i can click on one of the pieces, but when i do the piece does change color and i get an error in the shell as well (listed below) im not sure why im getting this and i was hoping you guys could give me better insight. Ill provide my code below as well and it is coded in python 3, thank you
builtins.IndexError: list index out of range
boardcirc =[[0,0,0,1,1,1,0,0,0],
[0,0,0,1,1,1,0,0,0],
[0,0,0,1,1,1,0,0,0],
[1,1,1,1,1,1,1,1,1],
[1,1,1,1,2,1,1,1,1],
[1,1,1,1,1,1,1,1,1],
[0,0,0,1,1,1,0,0,0],
[0,0,0,1,1,1,0,0,0],
[0,0,0,1,1,1,0,0,0]]
def HiQ():
splash_screen()
make_board()
def make_board():
make_sqr()
make_circ()
get_click()
def get_click():
global count, boardcirc
while 1!=0:
count = count - 1
displaymessage("Pieces: " + str(count))
where = win.getMouse()
col = where.x//90
row = where.y//90
valid_move(row,col)
make_move(row,col)
def valid_move(row,col):
if boardcirc[row][col] == 0:
return False
if boardcirc[row-1][col] == 1 and boardcirc[row-2][col] == 1:
return True
if boardcirc[row+1][col] == 1 and boardcirc[row+2][col] == 1:
return True
if boardcirc[row][col-1] == 1 and boardcirc[row][col-2] == 1:
return True
if boardcirc[row][col+1] == 1 and boardcirc[row][col+2] == 1:
return True
def make_move(row,col):
while valid_move(row,col) == True:
col = (col*85)+42
row = (row*85)+42
circ = Circle(Point(col,row),35)
circ.setFill("white")
circ.draw(win)
thats everything that applies to the error
For your valid_move(row,col), you can't have all those if statements.
Instead of doing this, use elif's after the initial if statement, and don't forget to write an else statement
if boardcirc[row][col] == 0:
return False
if boardcirc[row-1][col] == 1 and boardcirc[row-2][col] == 1:
return True
elif boardcirc[row+1][col] == 1 and boardcirc[row+2][col] == 1:
return True
elif boardcirc[row][col-1] == 1 and boardcirc[row][col-2] == 1:
return True
elif boardcirc[row][col+1] == 1 and boardcirc[row][col+2] == 1:
return True
else:
return False