Onvalue of Checkbutton always = 0 python I also use get() - python-3.x
I had two codes, since I combined them, chechbox always = 0
(When I run the code separately, it works fine)
from tkinter import *
from tkinter import messagebox
from tkinter import ttk
from convert_number2text import convert_ordinary
from pyperclip import copy, paste
import csv
from jdatetime import datetime, date
from show_factor import show_factors
from os import listdir
class Program:
def __init__(self):
self.root = Tk()
self.root.title("Accounting")
self.root.minsize(800, 600)
Button(self.root, text="فاکتور نوشتن", font=("",20),bg="red", command=self.factor_new).pack()
Button(self.root, text="فاکتور های ثبت شده", font=("",20),bg="red", command=show_factors).pack()
Button(self.root, text="افزودن کارت", font=("",20),bg="red").pack()
self.root.mainloop()
def show_factors():
win_show_factor = Tk()
win_show_factor.title("show factors")
win_show_factor.minsize(940, 600)
Label(win_show_factor, text="کد فاکتور", font=("",16)).place(x=760 ,y=10)
entry_code_factor = Entry(win_show_factor, font=("", 16), width=7)
entry_code_factor.place(x=755, y=40)
Label(win_show_factor, text="نام مشتری", font=("",16)).place(x=760, y=80)
entry_name_factor = Entry(win_show_factor, font=("", 16))
entry_name_factor.place(x=670, y=110)
Label(win_show_factor, text="اطلاعات فاکتور", font=("",16)).place(x=240, y=10)
entry_info_factor = Text(win_show_factor, font=("", 13), width=30, height=7)
entry_info_factor.place(x=160, y=40)
Label(win_show_factor, text="سال", font=("", 16)).place(x=540,y=5)
combo_y= ttk.Combobox(win_show_factor, values=["1400"])
for i in range(1401, 1420):
combo_y['values'] += (i,)
combo_y.set("1400")
combo_y.place(x=480,y=35)
Label(win_show_factor, text="ماه", font=("", 16)).place(x=540, y=60)
combo_m= ttk.Combobox(win_show_factor, values=["1"])
for i in range(2, 13):
combo_m['values'] += (i,)
combo_m.set("1")
combo_m.place(x=480, y=90)
Label(win_show_factor, text="روز", font=("", 16)).place(x=530, y=115)
combo_d= ttk.Combobox(win_show_factor, values=["1"])
for i in range(2, 32):
combo_d['values'] += (i,)
combo_d.set("1")
combo_d.place(x=480, y=150)
list_box_find = ttk.Treeview(win_show_factor, column=("c1", "c2", "c3", "c4", "c5"), show='headings')
list_box_find.column("# 1", anchor=CENTER,width=220)
list_box_find.heading("# 1", text="نام مشتری")
list_box_find.column("# 2", anchor=CENTER, width=60)
list_box_find.heading("# 2", text="کد فاکتور")
list_box_find.column("# 3", anchor=CENTER, width=150)
list_box_find.heading("# 3", text="تاریخ")
list_box_find.column("# 4", anchor=CENTER, width=100)
list_box_find.heading("# 4", text="مبلغ فاکتور")
list_box_find.column("# 5", anchor=CENTER, width=400)
list_box_find.heading("# 5", text="اطلاعات بیشتر")
list_box_find.place(x=3, y=200)
by_name = IntVar()
r1 = Checkbutton(win_show_factor, text="جستجو با نام مشتری", variable=by_name)
by_code = IntVar()
r1.place(x=10,y=10)
r2 = Checkbutton(win_show_factor, text="جستجو با کد فاکتور", variable=by_code)
by_date = IntVar()
r2.place(x=10, y=40)
r3 = Checkbutton(win_show_factor, text="جستجو با تاریخ", variable=by_date)
r3.place(x=10, y=70)
by_info = IntVar()
r4 = Checkbutton(win_show_factor, text="جستجو با اطلاعات", variable=by_info)
r4.place(x=10, y=100)
def search():
for item in list_box_find.get_children():
list_box_find.delete(item)
list_items = []
list_file = listdir(r"G:\check file\python\Accounting\factors")
for j in list_file:
file_csv = "G:/check file/python/Accounting/factors/{}".format(j)
with open(file_csv, encoding="utf-8") as Rfile_csv:
read_csv = csv.reader(Rfile_csv)
x = 0
for i in read_csv:
if x == 0:
name_moshtari = i[0]
Purchase_code = i[1]
tarikhe_buy = i[2]
price_all = i[3]
elif x == 1:
more_info = i[0]
poole_naghd = i[1]
poole_kart = i[2]
poole_nasiye = i[3]
else:
list_items.insert(len(list_items), i)
x +=1
name_check = name_moshtari.strip().find(entry_name_factor.get().strip())
info_check = -1
for i in more_info.split():
if i.find(entry_info_factor.get("1.0", END).strip()) != -1:
info_check = 0
code_check = Purchase_code.strip().find(entry_code_factor.get().strip())
date_check = -1
date_factor = tarikhe_buy[:tarikhe_buy.find(" ")]
date_find = date(int(combo_y.get()), int(combo_m.get()), int(combo_d.get()))
if str(date_find) == date_factor :
date_check = 0
d=1
c=1
n=1
f=1
print(by_code.get(),by_date.get(),by_info.get(),by_name.get())
if by_date.get():
d = 2
if by_code.get():
c = 3
if by_name.get():
n = 4
if by_info.get():
f = 5
j = d * c * n * f
if (j == 5) and (info_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 4) and (name_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 3) and (code_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 2) and (date_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 6) and (date_check != -1) and (code_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 8) and (date_check != -1) and (name_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 10) and (info_check != -1) and (date_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 12) and (name_check != -1) and (code_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 15) and (info_check != -1) and (code_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 20) and (info_check != -1) and (name_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 24) and (date_check != -1) and (code_check != -1) and (name_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 30) and (date_check != -1) and (code_check != -1) and (info_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 40) and (date_check != -1) and (name_check != -1) and (info_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 60) and (code_check != -1) and (name_check != -1) and (info_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 120) and (date_check != -1) and (name_check != -1) and (info_check != -1) and (code_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
Button(win_show_factor, text="search", font=("",16), command=search).place(x=30,y=130)
win_show_factor.mainloop()
def setting_app(self, x):
with open("setting.csv", encoding="utf-8") as setting_file:
read_setting = csv.reader(setting_file)
for i in read_setting:
print(i)
if x == 0:
return i[1]
elif x == 1:
if i[0] == "code_buy_end":
return i[1]
def code_buy(self):
now_code = self.setting_app(1)
code = int(now_code) + 1
with open("setting.csv", "w", encoding="utf-8", newline='') as setting_file:
write_setting = csv.writer(setting_file)
write_setting.writerows([["version", "1.0"],["code_buy_end", code]])
return code
def factor_new(self):
self.win_factor = Tk()
self.win_factor.title("factor")
self.win_factor.minsize(1000, 600)
Label(self.win_factor, text="نام مشتری", font=("",16)).place(x=820, y=8)
self.text_name_moshtari_input = Entry(self.win_factor, font=("",13), width=30)
self.text_name_moshtari_input.place(x=540, y=10)
Label(self.win_factor, font=("",14), text="نام محصول").place(x=230, y=30)
self.text_name_item_input = Entry(self.win_factor, font=("",13), width=23)
self.text_name_item_input.place(x=160, y=60)
Label(self.win_factor, font=("",14), text="تعداد/متر").place(x=380, y=30)
self.text_count_item_input = Entry(self.win_factor, font=("",13), width=5)
self.text_count_item_input.place(x=390, y=60)
Label(self.win_factor, font=("",14), text="قیمت واحد").place(x=465, y=30)
self.text_price_item_input = Entry(self.win_factor, font=("",13), width=10)
self.text_price_item_input.place(x=458, y=60)
self.text_price_item_input.insert(0, "0")
self.text_price_item = Label(self.win_factor, text= "", font=("",10))
self.text_price_item.place(x=428, y=85)
Label(self.win_factor, text="اطلاعات بیشتر فاکتور", font=("",16)).place(x=790,y=130)
self.text_info_more = Text(self.win_factor, width=25, height=18, font=("", 13))
self.text_info_more.place(x=750, y=175)
tree = ttk.Treeview(self.win_factor, column=("c1", "c2", "c3","c4"), show='headings', height=19)
tree.column("# 1", anchor=CENTER,width=220)
tree.heading("# 1", text="نام محصول")
tree.column("# 2", anchor=CENTER, width=70)
tree.heading("# 2", text="تعداد/متر")
tree.column("# 3", anchor=CENTER, width=110)
tree.heading("# 3", text="قیمت واحد")
tree.column("# 4", anchor=CENTER, width=150)
tree.heading("# 4", text="مجموع قیمت محصول")
tree.place(x=160, y=120)
self.my_list = Listbox(self.win_factor, height=23)
self.my_list.place(x=20, y=50)
self.text_name_item_total = Label(self.win_factor, text= "مجموع :", font=("",20))
self.text_name_item_total.place(x=150, y=535)
Label(self.win_factor, text=":", font=("",20)).place(x=380, y=527)
self.text_count_item_total = Label(self.win_factor, text= "0", font=("",16))
self.text_count_item_total.place(x=390, y=535)
self.text_price_item_total = Label(self.win_factor, text= "0", font=("",16))
self.text_price_item_total.place(x=615, y=535)
Label(self.win_factor, text=":", font=("",20)).place(x=565, y=527)
self.text_price_item_total_text = Label(self.win_factor, text= "", font=("",13))
self.text_price_item_total_text.place(x=460, y=560)
self.price_total = 0
self.count_total = 0
self.list_item =[]
def update(dete):
try:
self.text_price_item.configure(text=convert_ordinary(int(self.text_price_item_input.get())))
except:
self.text_price_item.configure(text="")
self.my_list.delete(0,END)
for item in dete:
self.my_list.insert(0, item)
def fillout(e):
self.text_name_item_input.delete(0, END)
self.text_name_item_input.insert(0, self.my_list.get(ACTIVE))
def check(e):
typed= self.text_name_item_input.get()
if typed == "":
dete = toppings
else:
dete= []
for item in toppings:
if typed.lower() in item.lower():
dete.append(item)
update(dete)
toppings = ["زانو سفید", "زانو سفید 2.5", "زانو سفید 3", "سراه سفید", "سراه سفید 2.5", "سراه سفید 3"]
update(toppings)
self.my_list.bind("<<ListboxSelect>>", fillout)
self.text_name_item_input.bind("<KeyRelease>", check)
self.text_price_item_input.bind("<KeyRelease>", check)
def delete_item():
tree.delete(tree.selection()[0])
self.list_item = []
for child in tree.get_children():
self.list_item.insert(0, tree.item(child)["values"])
print(self.list_item)
self.price_total = 0
self.count_total = 0
for i in range(0, len(self.list_item)):
self.count_total =self.count_total+ float(self.list_item[i][1])
self.price_total = self.price_total+ int(float(self.list_item[i][3]))
self.text_count_item_total.configure(text=self.count_total)
self.text_price_item_total.configure(text=self.price_total)
self.text_price_item_total_text.configure(text=convert_ordinary(self.price_total))
def edit_item():
xitem = tree.selection()[0]
h_info = tree.item(xitem,["values"].pop())
win_edit = Toplevel()
win_edit.title("تغییر {} به تعداد {} و مبلغ {}".format(h_info[0], h_info[1], h_info[2]))
win_edit.minsize(400, 250)
def ok_edit():
tree.item(xitem, values=(entry_name_item.get(), entry_count_item.get(), entry_price_item.get(), float(entry_count_item.get())* int(entry_price_item.get())))
self.list_item = []
for child in tree.get_children():
self.list_item.insert(0, tree.item(child)["values"])
self.price_total = 0
self.count_total = 0
for i in range(0, len(self.list_item)):
self.count_total =self.count_total+ float(self.list_item[i][1])
self.price_total = self.price_total+ int(float(self.list_item[i][3]))
self.text_count_item_total.configure(text=self.count_total)
self.text_price_item_total.configure(text=self.price_total)
self.text_price_item_total_text.configure(text=convert_ordinary(self.price_total))
win_edit.destroy()
Label(win_edit, text="نام محصول", font=("", 16)).place(x=80, y=10)
entry_name_item = Entry(win_edit, font=("", 16))
entry_name_item.place(x=20, y=40)
Label(win_edit, text="تعداد/متر", font=("", 16)).place(x=80, y=90)
entry_count_item = Entry(win_edit, font=("", 16))
entry_count_item.place(x=20, y=120)
Label(win_edit, text="قیمت واحد", font=("", 16)).place(x=80, y=160)
entry_price_item = Entry(win_edit, font=("", 16))
Button(win_edit, text="تایید", font=("",20), command=ok_edit, width=5).place(x=290, y=100)
entry_price_item.place(x=20, y=190)
win_edit.mainloop()
def add_item2list(event=None):
self.price_total = 0
self.count_total = 0
try:
price_all = int(self.text_price_item_input.get())*float(self.text_count_item_input.get())
tree.insert("", len(self.list_item), values=(self.text_name_item_input.get(), self.text_count_item_input.get(), self.text_price_item_input.get(),int(price_all)))
self.list_item.insert(len(self.list_item), (self.text_name_item_input.get(), self.text_count_item_input.get(), self.text_price_item_input.get(), int(price_all)))
self.text_price_item.configure(text=convert_ordinary(int(self.text_price_item_input.get())))
print(self.list_item)
for i in range(0, len(self.list_item)):
self.count_total =self.count_total+ float(self.list_item[i][1])
self.price_total = self.price_total+ int(float(self.list_item[i][3]))
self.text_count_item_total.configure(text=self.count_total)
self.text_price_item_total.configure(text=self.price_total)
self.text_price_item_total_text.configure(text=convert_ordinary(self.price_total))
self.text_name_item_input.delete(0,END)
self.text_name_item_input.focus()
if self.price_total != 0:
self.btn_accept_item_end.configure(state="active")
except:
messagebox.showerror("Error", "لطفا ورودی ها را صحیح وارد کنید")
self.price_naghd_end= 0
self.price_nasiye_end= 0
self.price_kart_end = 0
def accept_end():
win_factor_end = Toplevel(self.win_factor)
win_factor_end.title("Pay")
win_factor_end.minsize(600, 300)
win_factor_end.maxsize(600, 300)
self.amount_paid = self.price_total
def chortke(event=None):
if input_naghd.get() == "":
input_naghd.insert(0,"0")
elif input_naghd.cget("state")== "normal":
print("01",input_naghd.cget("state"))
self.price_naghd_end = int(input_naghd.get()) + self.price_naghd_end
input_naghd.configure(state="disabled")
self.amount_paid = self.amount_paid - self.price_naghd_end
if input_kart.get() == "":
input_kart.insert(0,"0")
elif input_kart.cget("state")== "normal":
print("02",input_kart.cget("state"))
self.price_kart_end = int(input_kart.get())+ self.price_kart_end
input_kart.configure(state="disabled")
self.amount_paid = self.amount_paid - self.price_kart_end
if input_nasiye.get() == "":
input_nasiye.insert(0,"0")
elif input_nasiye.cget("state")== "normal":
print("03",input_nasiye.cget("state"))
self.price_nasiye_end = int(input_nasiye.get()) + self.price_nasiye_end
input_nasiye.configure(state="disabled")
self.amount_paid = self.amount_paid - self.price_nasiye_end
text_price_end.configure(text=self.amount_paid)
text_price_end_tx.configure(text=convert_ordinary(int(self.amount_paid)))
if text_naghd.cget("text") == "":
text_naghd.configure(text=convert_ordinary(int(input_naghd.get())))
if text_kart.cget("text") == "":
text_kart.configure(text=convert_ordinary(int(input_kart.get())))
if text_nasiye.cget("text") == "":
text_nasiye.configure(text=convert_ordinary(int(input_nasiye.get())))
input_nasiye.delete(0,END)
input_kart.delete(0,END)
input_naghd.delete(0,END)
if self.amount_paid == 0:
btn_taeed.configure(state="active")
def space(event= None):
copy(self.amount_paid)
input_naghd.focus_get().insert(0, paste())
def save_factor():
try:
self.tarikh = datetime.now()
print(self.tarikh)
code = self.code_buy()
with open("factors/factor_{}.csv".format(code), "w", encoding="utf-8",newline='') as csv_save:
csv_write = csv.writer(csv_save)
csv_write.writerow([self.text_name_moshtari_input.get(), code, self.tarikh, self.price_total])
csv_write.writerow([ self.text_info_more.get("1.0", END), self.price_naghd_end, self.price_kart_end, self.price_nasiye_end])
for child in tree.get_children():
print(tree.item(child)["values"])
csv_write.writerow(tree.item(child)["values"])
messagebox.showinfo("save_compelect", "فاکتور با کد {} ذخیره شد".format(code))
win_factor_end.destroy()
self.win_factor.destroy()
except:
messagebox.showerror("Error", "!!مشکلی رخ داد فاکتور ذخیره نشد")
win_factor_end.bind("<Return>",chortke)
win_factor_end.bind("<space>",space)
btn_taeed = Button(win_factor_end, text="اوکی", font=("",13), state="disabled", command=save_factor)
btn_taeed.place(x=380, y=60)
text_price_end = Label(win_factor_end, text=self.price_total, font=("", 16))
text_price_end.place(x=110, y=220)
text_price_end_tx = Label(win_factor_end, text=convert_ordinary(int(self.price_total)), font=("", 16))
text_price_end_tx.place(x=110, y=260)
Label(win_factor_end, text="دریافت شود:", font=("", 16)).place(x=10, y=220)
btn_naghd = Button(win_factor_end, text="نقدی", font=("",16), command=chortke)
btn_naghd.place(x=40, y=20)
input_naghd = Entry(win_factor_end, font=("",16), width=10)
input_naghd.place(x=110,y=25)
text_naghd = Label(win_factor_end, text="", font=("",13))
text_naghd.place(x=240, y=26)
btn_kart = Button(win_factor_end, text="کارتخوان", font=("",16), command=chortke)
btn_kart.place(x=10, y=80)
input_kart = Entry(win_factor_end, font=("",16), width=10)
input_kart.place(x=110,y=85)
text_kart = Label(win_factor_end, text="", font=("",13))
text_kart.place(x=240, y=86)
btn_nasiye = Button(win_factor_end, text="نسیه", font=("",16), command=chortke)
btn_nasiye.place(x=45, y=140)
input_nasiye = Entry(win_factor_end, font=("",16), width=10)
input_nasiye.place(x=110,y=145)
text_nasiye = Label(win_factor_end, text="", font=("",13))
text_nasiye.place(x=240, y=146)
win_factor_end.mainloop()
self.btn_accept_item = Button(self.win_factor, text="تایید", font=("",16), command=add_item2list, width=10)
self.btn_accept_item.place(x=760, y=50)
self.win_factor.bind("<Return>", add_item2list)
self.btn_delete_item = Button(self.win_factor, text="delete", font=("",16), command=delete_item, width=10)
self.btn_delete_item.place(x=15, y=430)
self.btn_delete_item = Button(self.win_factor, text="edit", font=("",16), command=edit_item, width=10)
self.btn_delete_item.place(x=15, y=480)
self.btn_accept_item_end = Button(self.win_factor, text="تایید نهایی", font=("",16), state="disabled", command=accept_end, width=10)
self.btn_accept_item_end.place(x=810, y=540)
self.win_factor.mainloop()
run=Program()
Related
How to pass values from one thread to another thread Python?
I begin to code the python and I am not have more experience in syntax of python I want to send a value from the RFID reader. If it saves successfully, the PIR Motion Sensor will be disabled in a moment. and reworking within the specified time. If the temperature is measured And send the value to the function RFID Reader to record the temperature and the PIR Motion Sensor stops working as well. class Security: global dbHost global dbUser global dbPass global dbNameEmp global dbNameSecure dbHost = 'localhost' dbUser = 'root' dbPass = 'iTdev#2020' dbNameEmp = 'empinfo' dbNameSecure = 'secureinfo' def __init__(self): self.msg="" def Temperature(self): while True: GPIO.output(TRIG, False) time.sleep(0.5) GPIO.output(TRIG, True) time.sleep(0.01) GPIO.output(TRIG, False) while GPIO.input(ECHO) == 0 : pulse_start = time.time() while GPIO.input(ECHO) == 1 : pulse_end = time.time() pulse_duration = pulse_end - pulse_start distance = pulse_duration * 11150 distance = round(distance,2) if distance > 0 and distance < 3 : buzzer.on() time.sleep(0.1) buzzer.off() print ("Distance: %scm" % (distance)) #print "Ambient Temperature :", sensor.get_ambient() print ("Temperature: %.1fc" % (sensor.get_object_1())) msgTemp = ("%.1f" % (sensor.get_object_1())) w, h = textsize(msgTemp, font=proportional(CP437_FONT)) if w <= device.width: x = round((device.width - w) / 2) with canvas(device) as draw: text(draw, (x, 0), msgTemp, fill="white", font=proportional(CP437_FONT)) else: show_message(device, msgTemp, fill="white", font=proportional(CP437_FONT),scroll_delay=0.04) time.sleep(1) device.clear() def rfid_callback(self, state, dev): rfid_presented = "" keys = "X^1234567890XXXXqwertzuiopXXXXasdfghjklXXXXXyxcvbnmXXXXXXXXXXXXXXXXXXXXXXX" while True: r,w,x = select([dev], [], []) for event in dev.read(): if event.type==1 and event.value==1: if event.code==28: rfid_presented = rfid_presented.replace("X", "") travel = state.replace("Thread-", "") dbConnEmp = mysql.connect(host=dbHost, user=dbUser, passwd=dbPass, db=dbNameEmp) curEmp = dbConnEmp.cursor() curEmp.execute("Select RFidEmp FROM RFidMaster WHERE (RFidStatus = 1) AND RFidNumber = '%s'" % (rfid_presented)) resultRFid = curEmp.fetchone() if curEmp.rowcount != 1: # print("Access Denied." + travel) with canvas(device) as draw: text(draw, (0, 0), "None", fill="white", font=proportional(CP437_FONT)) time.sleep(0.5) device.clear() else: # print("Unlocking Door." + travel) dbConnSecure = mysql.connect(host=dbHost, user=dbUser, passwd=dbPass, db=dbNameSecure) curSecure = dbConnSecure.cursor() curSecure.execute("SELECT EntraId,DATE_FORMAT(CreateDate, '%Y%m%d') AS CreateDate FROM entranlog ORDER BY EntraId DESC, CreateDate DESC LIMIT 1") resultKey = curSecure.fetchone() KeyDate = time.strftime("%Y%m%d") if curSecure.rowcount != 1: KeyId = KeyDate+"0001" else: if resultKey[1] == KeyDate: iSum = int(resultKey[0]) def sum(x, y): return x + y KeyId = ('%d' % sum(iSum, 1)) else: KeyId = KeyDate+"0001" create_date = time.strftime('%Y-%m-%d %H:%M:%S') insertSecure = "INSERT INTO entranlog (EntraId,EntraAction,EntraStatus,CreateBy,CreateDate) VALUES (%s,%s,%s,%s,%s)" valSecure = (KeyId,travel,1,resultRFid[0],create_date) curSecure.execute(insertSecure, valSecure) dbConnSecure.commit() # print("Welcome: " + resultRFid[0]) with canvas(device) as draw: text(draw, (0, 0), "Hello", fill="white", font=proportional(CP437_FONT)) print(curSecure.rowcount, "record inserted.") time.sleep(0.8) device.clear() rfid_presented = "" else: rfid_presented += keys[ event.code ] def PirSensor(self): while True: led_blue.on() time.sleep(0.1) current_state = GPIO.input(pir_sensor) if current_state == 1: print("GPIO pin %s is %s" % (pir_sensor, current_state)) GPIO.output(relay_alarm,True) led_blue.off() led_red.blink(0.1, 0.2) # buzzer.beep(0.5, 0.5, 3) time.sleep(5) GPIO.output(relay_alarm,False) led_red.off() led_yellow.blink(0.5, 0.5) time.sleep(5) led_yellow.off() def main(self): devIn = threading.Thread(target=self.rfid_callback, args=['1', InputDevice('/dev/input/event0')]) devIn.start() devOut = threading.Thread(target=self.rfid_callback, args=['2', InputDevice('/dev/input/event1')]) devOut.start() Pir = threading.Thread(target=self.PirSensor) Pir.start() Temp = threading.Thread(target=self.Temperature) Temp.start() if __name__ == "__main__": g=Security() g.main()
Flappy Bird pygame base not defined
I'm currently finishing a Flappy Bird game in Python 3.8 that will be played by an AI that will learn by itself how to play the game and improve itself from its previous mistakes until a point where it will be "unbeatable". I'm really close to finish this but there's this error in my code: NameError: name 'base' is not defined This error wasn't appearing during the previous tests that I made. I looked into all the code that mentioned the base in the game but still, I couldn't find anything wrong. The game code is this: import pygame import neat import time import os import random pygame.font.init() WIN_WIDTH = 500 WIN_HEIGHT = 800 BIRD_IMGS = [pygame.transform.scale2x(pygame.image.load(os.path.join('imgs', 'bird1.png'))), pygame.transform.scale2x(pygame.image.load(os.path.join('imgs', 'bird2.png'))), pygame.transform.scale2x(pygame.image.load(os.path.join('imgs', 'bird3.png')))] PIPE_IMG = pygame.transform.scale2x(pygame.image.load(os.path.join('imgs', 'pipe.png'))) BASE_IMG = pygame.transform.scale2x(pygame.image.load(os.path.join('imgs', 'base.png'))) BG_IMG = pygame.transform.scale2x(pygame.image.load(os.path.join('imgs', 'bg.png'))) STAT_FONT = pygame.font.SysFont('comicsans', 50) class Bird: IMGS = BIRD_IMGS MAX_ROTATION = 25 ROT_VEL = 20 ANIMATION_TIME = 5 def __init__(self, x, y): self.x = x self.y = y self.tilt = 0 self.tick_count = 0 self.vel = 0 self.height = self.y self.img_count = 0 self.img = self.IMGS[0] def jump(self): self.vel = -10.5 self.tick_count = 0 self.height = self.y def move(self): self.tick_count += 1 d = self.vel * self.tick_count + 1.5 * self.tick_count ** 2 if d >= 16: d = 16 if d < 0: d -= 2 self.y = self.y + d if d < 0 or self.y < self.height + 50: if self.tilt < self.MAX_ROTATION: self.tilt = self.MAX_ROTATION else: if self.tilt > -90: self.tilt -= self.ROT_VEL def draw(self, win): self.img_count += 1 if self.img_count < self.ANIMATION_TIME: self.img = self.IMGS[0] elif self.img_count < self.ANIMATION_TIME*2: self.img = self.IMGS[1] elif self.img_count < self.ANIMATION_TIME*3: self.img = self.IMGS[2] elif self.img_count < self.ANIMATION_TIME*4: self.img = self.IMGS[1] elif self.img_count == self.ANIMATION_TIME*4 + 1: self.img = self.IMGS[0] self.img_count = 0 if self.tilt <= -80: self.img = self.IMGS[1] self.img_count = self.ANIMATION_TIME*2 rotated_image = pygame.transform.rotate(self.img, self.tilt) new_rect = rotated_image.get_rect(center=self.img.get_rect(topleft = (self.x, self.y)).center) win.blit(rotated_image, new_rect.topleft) def get_mask(self): return pygame.mask.from_surface(self.img) class Pipe: GAP = 200 VEL = 5 def __init__(self, x): self.x = x self.height = 0 self.top = 0 self.bottom = 0 self.PIPE_TOP = pygame.transform.flip(PIPE_IMG, False, True) self.PIPE_BOTTOM = PIPE_IMG self.passed = False self.set_height() def set_height(self): self.height = random.randrange(50, 450) self.top = self.height - self.PIPE_TOP.get_height() self.bottom = self.height + self.GAP def move(self): self.x -= self.VEL def draw(self, win): win.blit(self.PIPE_TOP, (self.x, self.top)) win.blit(self.PIPE_BOTTOM, (self.x, self.bottom)) def collide(self, bird): bird_mask = bird.get_mask() top_mask = pygame.mask.from_surface(self.PIPE_TOP) bottom_mask = pygame.mask.from_surface(self.PIPE_BOTTOM) top_offset = (self.x - bird.x, self.top - round(bird.y)) bottom_offset = (self.x - bird.x, self.bottom - round(bird.y)) b_point = bird_mask.overlap(bottom_mask, bottom_offset) t_point = bird_mask.overlap(top_mask, top_offset) if t_point or b_point: return True return False class Base: VEL = 5 WIDTH = BASE_IMG.get_width() IMG = BASE_IMG def __init__(self, y): self.y = y self.x1 = 0 self.x2 = self.WIDTH def move(self): self.x1 -= self.VEL self.x2 -= self.VEL if self.x1 + self.WIDTH < 0: self.x1 = self.x2 + self.WIDTH if self.x2 + self.WIDTH < 0: self.x2 = self.x1 + self.WIDTH def draw(self, win): win.blit(self.IMG, (self.x1, self.y)) win.blit(self.IMG, (self.x2, self.y)) def draw_window(win, bird, pipes, base, score): win.blit(BG_IMG, (0, 0)) for pipe in pipes: pipe.draw(win) text = STAT_FONT.render('Score: ' + str(score), 1, (255, 255, 255)) win.blit(text, (WIN_WIDTH - 10 - text.get_width(), 10)) base.draw(win) for bird in birds: bird.draw(win) pygame.display.update() def main(genomes, config): nets = [] ge = [] birds = [] for _, g in genomes: net = neat.nn.FeedForwardNetwork.create(g, config) nets.append(net) birds.append(Bird(230, 350)) g.fitness = 0 ge.append(g) pipes = [Pipe(600)] win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT)) clock = pygame.time.Clock() score = 0 run = True while run: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit() quit() pipe_ind = 0 if len(birds) > 0: if len(pipes) > 1 and birds[0].x > pipes[0].x + pipes[0].PIPE_TOP.get_width(): pipe_ind = 1 else: run = False break for x, bird in enumerate(birds): bird.move() ge[x].fitness += 0.1 output = nets[x].activate((bird.y, abs(bird.y - pipes[pipe_ind].height), abs(bird.y - pipes[pipe_ind].bottom))) if output[0] > 0.5: bird.jump() #bird.move() add_pipe = False rem = [] for pipe in pipes: for x, bird in enumerate(birds): if pipe.collide(bird): ge[x].fitness -= 1 birds.pop(x) nets.pop(x) ge.pop(x) if not pipe.passed and pipe.x < bird.x: pipe.passed = True add_pipe = True if pipe.x + pipe.PIPE_TOP.get_width() < 0: rem.append(pipe) pipe.move() if add_pipe: score += 1 for g in ge: g.fitness += 5 pipes.append(Pipe(600)) for r in rem: pipes.remove(r) for x, bird in enumerate(birds): if bird.y + bird.img.get_height() >= 730 or bird.y < 0: birds.pop(x) nets.pop(x) ge.pop(x) base.move() draw_window(win, birds, pipes, base, score) def run(config_path): config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, config_path) p = neat.Population(config) p.add_reporter(neat.StdOutReporter(True)) stats = neat.StatisticsReporter() p.add_reporter(stats) winner = p.run(main, 50) if __name__ == '__main__': local_dir = os.path.dirname(__file__) config_path = os.path.join(local_dir, 'config-feedforward.txt') run(config_path) And sorry for the such long code, you might want to press Ctrl+F to find all the locations of the base element in the code, and I thank you for the help in advance. PS: The Base is the floor of the game.
You missed to create an instance of Base in main(). e.g: def main(genomes, config): # [...] base = Base(0)
My code wont run properly when other files try to use it
So my code as been acting up and I don't know what the problem is. When I try to test the file "Battle" it works like it supposed to and everything is fine. It pulls up a tkinter window like I want to, shows the buttons, My sprites, etc. But when I use my main file to run the Battle file it doesn't show the buttons, listbox, or sprites. I looked all over my code and I cant find out whats wrong. If anyone could help me then that would be great! It's a lot of code and I am kinda a rookie so it may not be the cleanest but I do leave a lot of notes. This is the Battle code: import tkinter as tk import random import time inBattle = False gameOver = True i = 0 enemy_type = 0 MAX_HP = 60 MAX_MP = 40 HPval = 20 MPval = 30 POTIONSval = 3 #test def add_text(recap): global i recap.insert(0, 'Damage: ' + str(i)) i += 1 #switch to turn the whole thing on or off def GameOver(): global gameOver if gameOver == True: gameOver = False else: gameOver = True #spells def Cast_Fireball(spells, MP, recap): global MPval if MPval - 10 > 0 or MPval - 10 == 0: MPval -= 10 MP.config(text='MP: ' + str(MPval)) hit = random.randint(0, 100) damage = random.randint(1,10) # 1d10 if hit > 9: # 90% recap.insert(0, 'Hit for ' + str(damage)) spells.destroy() else: recap.insert(0, 'Missed!') spells.destroy() else: recap.insert(0, 'Not enough mana.') spells.destroy() def Cast_Iceball(spells, MP, recap): global MPval if MPval - 12 > 0 or MPval - 12 == 0: MPval -= 12 MP.config(text='MP: ' + str(MPval)) hit = random.randint(0, 100) damage = random.randint(1,6) * 2 # 2d6 if hit > 4: # 95% recap.insert(0, 'Hit for ' + str(damage)) spells.destroy() else: recap.insert(0, 'Missed!') spells.destroy() else: recap.insert(0, 'Not enough mana.') spells.destroy() def Cast_Heal(spells, HP, MP, recap): global MPval global HPval if MPval - 15 > 0 or MPval - 15 == 0: if HPval < MAX_HP: MPval -= 15 MP.config(text='MP: ' + str(MPval)) damage = random.randint(7,25) # 2d10 + 5 if HPval + damage > MAX_HP: damage = MAX_HP - HPval recap.insert(0, 'Healed for ' + str(damage)) HPval += damage HP.config(text='HP: ' + str(HPval)) spells.destroy() else: recap.insert(0, 'Not enough mana.') spells.destroy() def Cast_Drain(spells, MP, recap): global MPval hit = random.randint(0, 100) damage = random.randint(1,6) # 1d6 if hit > 19: # 80% recap.insert(0, 'Hit for ' + str(damage)) recap.insert(0, 'Recovered some mana!') MPval += damage MP.config(text='MP: ' + str(MPval)) spells.destroy() else: recap.insert(0, 'Missed!') spells.destroy() #activates window for spell list def Spell_list(HP, MP, recap): spells = tk.Tk() spells.title("Spell List") spells.minsize(150,168) Fireball = tk.Button(spells, text='Fireball', bg='black', font=("arial", 15, "bold"), fg="white", width=12, command= lambda: Cast_Fireball(spells, MP, recap)) Fireball.pack() Iceball = tk.Button(spells, text='Iceball', bg='black', font=("arial", 15, "bold"), fg="white", width=12, command= lambda: Cast_Iceball(spells, MP, recap)) Iceball.pack() Mana_Drain = tk.Button(spells, text='Mana Drain', bg='black', font=("arial", 15, "bold"), fg="white", width=12, command= lambda: Cast_Drain(spells, MP, recap)) Mana_Drain.pack() Crude_Heal = tk.Button(spells, text='Crude Heal', bg='black', font=("arial", 15, "bold"), fg="white", width=12, command= lambda: Cast_Heal(spells, HP, MP, recap)) Crude_Heal.pack() spells.mainloop() #drinks a max hp potion and checks if your full already and doesn't use it def Drink_Potion(HP,POTIONS,recap): global HPval global POTIONSval if POTIONSval > 0 and HPval < MAX_HP: temp = MAX_HP - HPval HPval = MAX_HP POTIONSval -= 1 recap.insert(0, 'Healed for ' + str(temp)) HP.config(text="HP: " + str(HPval)) POTIONS.config(text="Potions: " + str(POTIONSval)) #main fucntion def Battle(): #trigger so the player on the other screen is stopped and cant move global inBattle global HPval global MPval global POTIONSval global enemy_type inBattle = True #screen settings screen = tk.Tk() screen.title("Encounter") screen.minsize(1000,500) screen.configure(bg='black') #background settings and rectangle for the bottom half of screen canvas = tk.Canvas(screen, width=1000, height=500) canvas.configure(bg='black') canvas.pack() canvas.create_rectangle(3,300,1000,500,fill='white') sprites = tk.Canvas(screen, width=200, height=200, bg='black') sprites.place(x=285, y=50) #choses which enemy to fight #enemy_type = random.randint(0,6) #spawning of the enemy if enemy_type == 0: img = tk.PhotoImage(file='sprites/slime.png') sprites.create_image(20,20, image=img, anchor="nw") #box on right to list the past actions recap = tk.Listbox(screen, font=("arial", 14), bg="white", width=22, height=12) recap.place(x=754, y=10) #trackers for health, mana, and potions HP = tk.Label(screen, text="HP: " + str(HPval), font=("arial",30), bg="white") HP.place(x=775, y=310) MP = tk.Label(screen, text="MP: " + str(MPval), font=("arial",30), bg="white") MP.place(x=775, y=360) Potions = tk.Label(screen, text="Potions: " + str(POTIONSval), font=("arial",30), bg="white") Potions.place(x=775, y=410) #buttons for commands Attack = tk.Button(screen,text="Attack",width=9, height=4, bg="black", fg="white", font=("arial", 24, "bold"), command= lambda: add_text(recap)) Attack.place(x=10, y= 313) Defend = tk.Button(screen,text="Defend",width=9, height=4, bg="black", fg="white", font=("arial", 24, "bold")) Defend.place(x=200, y= 313) Item = tk.Button(screen,text="Item",width=9, height=4, bg="black", fg="white", font=("arial", 24, "bold"), command= lambda: Drink_Potion(HP, Potions, recap)) Item.place(x=390, y= 313) Magic = tk.Button(screen,text="Magic",width=9, height=4, bg="black", fg="white", font=("arial", 24, "bold"), command= lambda: Spell_list(HP, MP, recap)) Magic.place(x=580, y= 313) screen.mainloop() #testing purposes / comment out on release #Battle() This is the Main code: import random import turtle import tkinter as tk import time import Battle callOnce = False GWIDTH = 800 GHEIGHT = 800 SWIDTH = 50 SHEIGHT = 50 START_Y = 0 END_Y = 0 PLAYER_X = 0 PLAYER_Y = 0 BUFFER = 80 DungeonCord = [] DungeonStorage = [] Treasure = [] pathingPlaces = [] pathingAmount = 0 start = tk.Tk() start.title("Dungeon Generator") start.minsize(500,500) #generate function making it save the set x and y and passing it to the turtle functions def Generate(): global GHEIGHT global GWIDTH Battle.GameOver() GWIDTH = xInsert.get() GHEIGHT = yInsert.get() start.destroy() DunGenText = tk.Label(text="Dungeon Generator", relief="solid", width = 20, font=("arial", 24, "bold")) DunGenText.place(x=60, y=35) xLabel = tk.Label(text="X Grid Count:", width = 10, font=("arial", 14)) xLabel.place(x=145,y=145) xInsert = tk.Entry(start, width=5) xInsert.place(x=280,y=150) yLabel = tk.Label(text="Y Grid Count:", width = 10, font=("arial", 14)) yLabel.place(x=145,y=245) yInsert = tk.Entry(start, width=5) yInsert.place(x=280,y=250) button = tk.Button(start,text="Generate",width=30, bg="black", fg="white", command=Generate) button.place(x=135, y=450) start.mainloop() #main loop for the turtle side of things while not Battle.gameOver: #window settings wn = turtle.Screen() wn.title("Dungeon Crawler") wn.setup(width=(int(GWIDTH) * int(SWIDTH))+BUFFER, height=(int(GHEIGHT) * int(SHEIGHT))+BUFFER) wn.bgcolor("black") wn.tracer(0) #where the grid would start to draw itself Gridx = (int(GWIDTH) * int(SWIDTH) * -1) / 2 Gridy = (int(GHEIGHT) * int(SHEIGHT)) /2 #this will determine the lowest number between the x axis and the y axis if int(GWIDTH) > int(GHEIGHT): LOWEST = int(GHEIGHT) else: LOWEST = int(GWIDTH) #this is the formula for the dungeon count in the grid // ((x * y) - 2y) / l DCOUNT = ((int(GHEIGHT) * int(GWIDTH)) - (2 * int(GHEIGHT))) / int(LOWEST) #the function to draw the grid def draw_grid(t, x, y, sx, sy,): for i in range(int(y)): for j in range(int(x)): t.penup() t.goto(x= Gridx + (sx * int(j)), y= Gridy - (sy * int(i))) t.pendown() t.forward(sx) t.right(90) t.forward(sx) t.right(90) t.forward(sx) t.right(90) t.forward(sx) t.right(90) #function to draw a square at a location def draw_square(t, s): for i in range(4): t.forward(int(s) * 20) t.right(90) #drawing the circle on the left side that would be the start def draw_start(t, t2): global START_Y global PLAYER_Y START_Y = random.randint(0, int(GHEIGHT) - 1) PLAYER_Y = START_Y t.penup() t.goto(x= Gridx + (SWIDTH / 2), y= (Gridy - (SHEIGHT / 2)) - (SHEIGHT * START_Y) - 10) t.pendown() t.circle(10) t2.penup() t2.goto(x= Gridx + (SWIDTH / 2), y= (Gridy - (SHEIGHT / 2)) - (SHEIGHT * START_Y)) t2.pendown() draw_player(t2) #drawing a circle on the right side that would be the end def draw_end(t): global END_Y END_Y = random.randint(0, int(GHEIGHT) - 1) t.penup() t.goto(x= (Gridx + (SWIDTH / 2)) * -1, y= (Gridy - (SHEIGHT / 2)) - (SHEIGHT * END_Y) - 10) t.pendown() t.circle(10) #draws the player at its location def draw_player(t): t.penup() t.goto(x= (Gridx + (SWIDTH / 2)) + (SWIDTH * PLAYER_X) - 10, y= (Gridy - (SHEIGHT / 2)) - (SHEIGHT * PLAYER_Y)+3) t.pendown() for i in range(50): t.forward(20) t.right(144) #drawing the dungeon at random locations that can be anyware between the entrance and the exit. def draw_dungeons(t, d): global DungeonCord global Treasure for i in range(int(d)): closestX = random.randint(1, int(GWIDTH) - 2) closestY = random.randint(0, int(GHEIGHT) - 1) DungeonCord.append((closestX,closestY)) DungeonStorage.append((closestX,closestY)) for j in range(i): if DungeonCord[j] == DungeonCord[i]: closestX = random.randint(1, int(GWIDTH) - 2) closestY = random.randint(0, int(GHEIGHT) - 1) DungeonCord[i] = (closestX,closestY) DungeonStorage[i] = (closestX,closestY) if DungeonCord[j] == DungeonCord[i]: closestX = random.randint(1, int(GWIDTH) - 2) closestY = random.randint(0, int(GHEIGHT) - 1) DungeonCord[i] = (closestX,closestY) DungeonStorage[i] = (closestX,closestY) #treasure room chance TR = random.randint(1,5) if TR == 5: t.color("yellow") Treasure.append(DungeonCord[i]) t.penup() t.goto(x= (Gridx + (SWIDTH / 2)) + (SWIDTH * closestX) - 10, y= (Gridy - (SHEIGHT / 2)) - (SHEIGHT * closestY) + 10) t.pendown() draw_square(t, 1) t.color("white") #the pathmaking function that would go to each dungeon and from the start to the end def draw_path(t): global DungeonCord global START_Y global END_Y global DCOUNT global pathingAmount global pathingPlaces t.penup() t.goto(x= Gridx + (SWIDTH / 2), y= (Gridy - (SHEIGHT / 2)) - (SHEIGHT * START_Y)) t.pendown() myCordsx = 0 myCordsy = START_Y dungeon = 0 for j in range(int(DCOUNT)): traveling = True closestX = 500 closestY = 500 #finds the closest dungeon for i in range(int(DCOUNT)): x, y = DungeonCord[i] if abs(x - myCordsx) + abs(y - myCordsy) < abs(closestX - myCordsx) + abs(closestY - myCordsy): closestX, closestY = x, y dungeon = i elif abs(x - myCordsx) + abs(y - myCordsy) == abs(closestX - myCordsx) + abs(closestY - myCordsy): if x < closestX: closestX, closestY = x, y dungeon = i #path to the current closest dungeon while traveling: if closestX > myCordsx: #path right t.forward(int(SWIDTH)) myCordsx += 1 pathingPlaces.append((myCordsx, myCordsy)) pathingAmount +=1 elif closestY > myCordsy: #path down t.right(90) t.forward(int(SWIDTH)) t.left(90) myCordsy += 1 pathingPlaces.append((myCordsx, myCordsy)) pathingAmount +=1 elif closestX < myCordsx: #path left t.right(180) t.forward(int(SWIDTH)) t.left(180) myCordsx -= 1 pathingPlaces.append((myCordsx, myCordsy)) pathingAmount +=1 elif closestY < myCordsy: #path up t.left(90) t.forward(int(SWIDTH)) t.right(90) myCordsy -= 1 pathingPlaces.append((myCordsx, myCordsy)) pathingAmount +=1 else: traveling = False i = 0 #reset on counter DungeonCord[dungeon] = (99, 99) #null entry / dungeon is checked off #pathing to the end traveling = True while traveling: if int(GWIDTH) - 1 > myCordsx: #going right t.forward(int(SWIDTH)) myCordsx += 1 pathingPlaces.append((myCordsx, myCordsy)) pathingAmount +=1 elif END_Y > myCordsy: #going down t.right(90) t.forward(int(SWIDTH)) t.left(90) myCordsy += 1 pathingPlaces.append((myCordsx, myCordsy)) pathingAmount +=1 elif int(GWIDTH) - 1 != myCordsx and END_Y == myCordsy: #going left t.right(180) t.forward(int(SWIDTH)) t.left(180) myCordsx -= 1 pathingPlaces.append((myCordsx, myCordsy)) pathingAmount +=1 elif int(GWIDTH) - 1 == myCordsx and END_Y != myCordsy: #going up t.left(90) t.forward(int(SWIDTH)) t.right(90) myCordsy -= 1 pathingPlaces.append((myCordsx, myCordsy)) pathingAmount +=1 else: traveling = False #all the turtle units involved in drawing grid = turtle.Turtle() grid.hideturtle() grid.pencolor("white") entrance = turtle.Turtle() entrance.hideturtle() entrance.pencolor("green") end = turtle.Turtle() end.hideturtle() end.pencolor("red") dun = turtle.Turtle() dun.hideturtle() dun.pencolor("white") dun.shape("square") path = turtle.Turtle() path.hideturtle() path.pencolor("green") player = turtle.Turtle() player.hideturtle() player.pencolor("pink") #player movement def moveUP(): global PLAYER_X global PLAYER_Y for i in range(pathingAmount): if (PLAYER_X, PLAYER_Y - 1) == pathingPlaces[i] and not Battle.inBattle: PLAYER_Y -= 1 player.clear() draw_player(player) for i in range(int(DCOUNT)): if (PLAYER_X, PLAYER_Y) == DungeonStorage[i]: Battle.Battle() break def moveDOWN(): global PLAYER_X global PLAYER_Y for i in range(pathingAmount): if (PLAYER_X, PLAYER_Y + 1) == pathingPlaces[i] and not Battle.inBattle: PLAYER_Y += 1 player.clear() draw_player(player) for i in range(int(DCOUNT)): if (PLAYER_X, PLAYER_Y) == DungeonStorage[i]: Battle.Battle() break def moveLEFT(): global PLAYER_X global PLAYER_Y for i in range(pathingAmount): if (PLAYER_X - 1, PLAYER_Y) == pathingPlaces[i] and not Battle.inBattle: PLAYER_X -= 1 player.clear() draw_player(player) for i in range(int(DCOUNT)): if (PLAYER_X, PLAYER_Y) == DungeonStorage[i]: Battle.Battle() break def moveRIGHT(): global PLAYER_X global PLAYER_Y for i in range(pathingAmount): if (PLAYER_X + 1, PLAYER_Y) == pathingPlaces[i] and not Battle.inBattle: PLAYER_X += 1 player.clear() draw_player(player) for i in range(int(DCOUNT)): if (PLAYER_X, PLAYER_Y) == DungeonStorage[i]: Battle.Battle() break #a call once function so the dungeons, start, and end doesn't keep drawing. if callOnce == False: draw_grid(grid, GWIDTH, GHEIGHT, SWIDTH, SHEIGHT) draw_start(entrance, player) draw_end(end) draw_dungeons(dun, DCOUNT) draw_path(path) callOnce = True wn.listen() wn.onkey(moveRIGHT, "d") wn.onkey(moveUP, "w") wn.onkey(moveLEFT, "a") wn.onkey(moveDOWN, "s") while True: wn.update()
Never Mind, the problem was tkinter itself. Just needed to change the tk.Tk() in my battle code to tk.Toplevel() since you cant have two tk.Tk() code. Well..... Damn
Display multiple images in PIL
-------------------------------Solved(Partially)---------------------------------------- My problem is that when I try to display multiple images on the canvas using PIL, I end up with only the last image. All the images have slightly different characteristics(angle offset). Also the having a plethora of entries, I have to use a loop for sure. Also I'll need to use PIL(tkinter objects not possible) for the angle offset feature. Here is the code; #!/usr/bin/python # Filename: weather_sim.py import os import tkinter as tk import h5py as hp import numpy as np import ntpath as ntp from PIL import Image, ImageTk from tkinter.filedialog import askopenfilename def path_leaf(path): head, tail = ntp.split(path) return tail or ntp.basename(head) class CoordFind: def __init__(self): self.LatPx = 0 self.LonPx = 0 def find_px(self, Lat, Lon): self.LatPx = (Lat - LatN)/LatLc self.LonPx = (Lon - LonW)/LonLc class PlottingGUI(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.coord = CoordFind() self.root = parent self.root.wm_title("-|-|-|-|||Wind Vector Plotter|||-|-|-|-") self.root.resizable(False, False) self.path = "None Selected" self.HaM = 0 self.Lat = 0 self.Lon = 0 self.WiD = 0 self.WiS = 0 self.fr = tk.Frame(self.root, width = (width+20), height = (height+20), bd = 2) self.fr.grid(row = 1, column = 0) self.frBro = tk.Frame(self.root, width = (width+20), height = 50, bd = 2) self.frBro.grid(row = 0, column = 0) self.frHi = tk.Frame(self.root, width = (width+20), height = 50, bd = 2) self.frHi.grid(row = 2, column = 0) self.cv = tk.Canvas(self.fr, width = width, height = height, background = "white", bd = 0, relief = tk.SUNKEN) self.cv.grid(row = 0, column = 0) self.cv.create_image(1, 1, anchor = "nw", image = photo) self.broButton = tk.Button(self.frBro, text = "Browse Dsets", command = self.analyseDset, height = 3, width = 16, bg = "yellow") self.broButton.grid(row = 0, column = 0, padx = 20) self.selFile = tk.Label(self.frBro, text = self.path) self.selFile.grid(row = 0, column = 1) self.caution = tk.Label(self.frHi, text = "Optional use. Warning!!, May lead to lags in program", fg = "red") self.caution.grid(row = 0, column = 1) self.shoRedBut = tk.Button(self.frHi, text = "Show H1", command = self.show_barbs1().__next__, height = 3, width = 16, bg = "#FF0000", fg = "white", activebackground="#E533B5") self.shoRedBut.grid(row = 1, column = 0, padx = 7, pady = 2) self.shoGrnBut = tk.Button(self.frHi, text = "Show H2", command = self.show_barbs2().__next__, height = 3, width = 16, bg = "#00B400", fg = "white", activebackground="#B5E533") self.shoGrnBut.grid(row = 1, column = 1, padx = 7, pady = 2) self.shoBluBut = tk.Button(self.frHi, text = "Show H3", command = self.show_barbs3().__next__, height = 3, width = 16, bg = "#0000FF", fg = "white", activebackground="#33B5E5") self.shoBluBut.grid(row = 1, column = 2, padx = 7, pady = 2) self.desc1 = tk.Label(self.frHi, text = "100-250 hPa", fg = "white", bg = "black") self.desc1.grid(row = 2, column = 0) self.desc2 = tk.Label(self.frHi, text = "250-350 hPa", fg = "white", bg = "black") self.desc2.grid(row = 2, column = 1) self.desc3 = tk.Label(self.frHi, text = "350-700 hPa", fg = "white", bg = "black") self.desc3.grid(row = 2, column = 2) def analyseDset(self): self.path = askopenfilename(filetypes = (("Dataset files", "*.h5") ,("All files", "*.*") )) self.jfname = path_leaf(self.path) self.selFile = tk.Label(self.frBro, text = self.jfname) self.selFile.grid(row = 0, column = 1) self.extDset() def extDset(self): hf = hp.File(self.path, 'r') HaM = hf.get('HEIGHT_ASSIGNMENT_METHOD') Lat = hf.get('Latitude') Lon = hf.get('Longitude') WiD = hf.get('WIND_DIRECTION') WiS = hf.get('WIND_SPEED') self.HaM = np.array(HaM) self.Lat = np.array(Lat)/100 self.Lon = np.array(Lon)/100 self.WiD = np.array(WiD) self.WiS = np.array(WiS) self.BrbImR = np.empty((self.HaM.shape[0],1)) self.BrbImB = np.empty((self.HaM.shape[0],1)) def show_barbs1(self): self.coord = CoordFind() script_dir = os.path.dirname(os.path.abspath(__file__)) im = Image.open(os.path.join(script_dir, 'Red_Barbs\icons8-wind-speed-43-47-50.png')) w, h = im.size im = im.resize((int(w/2), int(h/2)), Image.ANTIALIAS) vec_im = ImageTk.PhotoImage(im.rotate(45)) for i in range(0, self.HaM.shape[0]): if self.HaM[i] == 0: self.coord.find_px(self.Lat[i], self.Lon[i]) x = self.coord.LonPx y = self.coord.LatPx self.BrbImR[i] = self.cv.create_image(x, y, image = vec_im) while True: for i in range(0, self.HaM.shape[0]): self.cv.itemconfigure(self.BrbImR[i], state = tk.NORMAL) self.shoRedBut.configure(text = "Showing H1") yield def show_barbs2(self): self.coord = CoordFind() BrbImG = np.empty((self.HaM.shape[0],1)) script_dir = os.path.dirname(os.path.abspath(__file__)) im = Image.open(os.path.join(script_dir, 'Green_Barbs\icons8-wind-speed-43-47-50.png')) w, h = im.size im = im.resize((int(w/2), int(h/2)), Image.ANTIALIAS) for i in range(0, self.HaM.shape[0]): if self.HaM[i] == 1: vec_im = ImageTk.PhotoImage(im.rotate(self.WiD[i])) self.coord.find_px(self.Lat[i], self.Lon[i]) x = self.coord.LonPx y = self.coord.LatPx BrbImG[i] = self.cv.create_image(x, y, image = vec_im) while True: for i in range(0, self.HaM.shape[0]): self.cv.itemconfigure(BrbImG[i], state = tk.NORMAL) self.shoGrnBut.configure(text = "Showing H2") yield def show_barbs3(self): self.coord = CoordFind() script_dir = os.path.dirname(os.path.abspath(__file__)) im = Image.open(os.path.join(script_dir, 'Blue_Barbs\icons8-wind-speed-43-47-50.png')) w, h = im.size im = im.resize((int(w/2), int(h/2)), Image.ANTIALIAS) vec_im = ImageTk.PhotoImage(im.rotate(180)) for i in range(0, self.HaM.shape[0]): if self.HaM[i] == 2: self.coord.find_px(self.Lat[i], self.Lon[i]) x = self.coord.LonPx y = self.coord.LatPx self.BrbImB[i] = self.cv.create_image(x, y, image = vec_im) while True: for i in range(0, self.HaM.shape[0]): self.cv.itemconfigure(self.BrbImB[i], state = tk.NORMAL) self.shoBluBut.configure(text = "Showing H3") yield if __name__ == "__main__": root = tk.Tk() backmap = "Map.png" photo = ImageTk.PhotoImage(file = backmap) width = photo.width() height = photo.height() LatN = 69.5 LatS = -69.3 LonE = 148.9 LonW = 1.0 LatLc = (LatS - LatN)/height LonLc = (LonE - LonW)/width app = PlottingGUI(root) root.mainloop() The output currently is this;(For the green arrows as that is what I have tested on) This is what I want;(But with different angles) I am using Python 3.6 on Windows 10. Thanks in advance!! P.S.: Also there is another problem if someone can help me with that. I would like to be able to choose a particular image based on a range factor(Wind Speed) by doing like a switch-case(or if-elif-else) procedure if possible. But when I try to do that it says "No such File or Directory". I may put it in another Question though. -------------------------------Solved(Till this point)--------------------------------- EDIT: Solved the problem of displaying multiple arrows according to choice and at different angles. Here's the code; #!/usr/bin/python # Filename: weather_sim.py import os import tkinter as tk import h5py as hp import numpy as np import ntpath as ntp from PIL import Image, ImageTk from tkinter.filedialog import askopenfilename def path_leaf(path): head, tail = ntp.split(path) return tail or ntp.basename(head) class CoordFind: def __init__(self): self.LatPx = 0 self.LonPx = 0 def find_px(self, Lat, Lon): self.LatPx = (Lat - LatN)/LatLc self.LonPx = (Lon - LonW)/LonLc class PlottingGUI(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.coord = CoordFind() self.root = parent self.root.wm_title("-|-|-|-|||Wind Vector Plotter|||-|-|-|-") self.root.resizable(False, False) self.path = "None Selected" self.HaM = 0 self.Lat = 0 self.Lon = 0 self.WiD = 0 self.WiS = 0 self.ima = [] self.fr = tk.Frame(self.root, width = (width+20), height = (height+20), bd = 2) self.fr.grid(row = 1, column = 0) self.frBro = tk.Frame(self.root, width = (width+20), height = 50, bd = 2) self.frBro.grid(row = 0, column = 0) self.frHi = tk.Frame(self.root, width = (width+20), height = 50, bd = 2) self.frHi.grid(row = 2, column = 0) self.cv = tk.Canvas(self.fr, width = width, height = height, background = "white", bd = 0, relief = tk.SUNKEN) self.cv.grid(row = 0, column = 0) self.cv.create_image(1, 1, anchor = "nw", image = photo) self.broButton = tk.Button(self.frBro, text = "Browse Dsets", command = self.analyseDset, height = 3, width = 16, bg = "yellow") self.broButton.grid(row = 0, column = 0, padx = 20) self.selFile = tk.Label(self.frBro, text = self.path) self.selFile.grid(row = 0, column = 1) self.caution = tk.Label(self.frHi, text = "Optional use. Warning!!, May lead to lags in program", fg = "red") self.caution.grid(row = 0, column = 1) self.shoRedBut = tk.Button(self.frHi, text = "Show H1", command = self.show_barbs1().__next__, height = 3, width = 16, bg = "#FF0000", fg = "white", activebackground="#E533B5") self.shoRedBut.grid(row = 1, column = 0, padx = 7, pady = 2) self.shoGrnBut = tk.Button(self.frHi, text = "Show H2", command = self.show_barbs2().__next__, height = 3, width = 16, bg = "#00B400", fg = "white", activebackground="#B5E533") self.shoGrnBut.grid(row = 1, column = 1, padx = 7, pady = 2) self.shoBluBut = tk.Button(self.frHi, text = "Show H3", command = self.show_barbs3().__next__, height = 3, width = 16, bg = "#0000FF", fg = "white", activebackground="#33B5E5") self.shoBluBut.grid(row = 1, column = 2, padx = 7, pady = 2) self.desc1 = tk.Label(self.frHi, text = "100-250 hPa", fg = "white", bg = "black") self.desc1.grid(row = 2, column = 0) self.desc2 = tk.Label(self.frHi, text = "250-350 hPa", fg = "white", bg = "black") self.desc2.grid(row = 2, column = 1) self.desc3 = tk.Label(self.frHi, text = "350-700 hPa", fg = "white", bg = "black") self.desc3.grid(row = 2, column = 2) def analyseDset(self): self.path = askopenfilename(filetypes = (("Dataset files", "*.h5") ,("All files", "*.*") )) self.jfname = path_leaf(self.path) self.selFile = tk.Label(self.frBro, text = self.jfname) self.selFile.grid(row = 0, column = 1) self.extDset() def extDset(self): hf = hp.File(self.path, 'r') HaM = hf.get('HEIGHT_ASSIGNMENT_METHOD') Lat = hf.get('Latitude') Lon = hf.get('Longitude') WiD = hf.get('WIND_DIRECTION') WiS = hf.get('WIND_SPEED') self.HaM = np.array(HaM) self.Lat = np.array(Lat)/100 self.Lon = np.array(Lon)/100 self.WiD = np.array(WiD) self.WiS = np.array(WiS) self.BrbImR = np.empty((self.HaM.shape[0],1)) self.BrbImG = np.empty((self.HaM.shape[0],1)) self.BrbImB = np.empty((self.HaM.shape[0],1)) def barb_def(self, WiS): if WiS < 1: self.ima = "1.png" elif WiS < 3: self.ima = "2.png" elif WiS < 8: self.ima = "3.png" elif WiS < 13: self.ima = "4.png" elif WiS < 18: self.ima = "5.png" elif WiS < 23: self.ima = "6.png" elif WiS < 28: self.ima = "7.png" elif WiS < 33: self.ima = "8.png" elif WiS < 38: self.ima = "9.png" elif WiS < 43: self.ima = "10.png" elif WiS < 48: self.ima = "11.png" elif WiS < 53: self.ima = "12.png" elif WiS < 58: self.ima = "13.png" elif WiS < 63: self.ima = "14.png" elif WiS < 68: self.ima = "15.png" elif WiS < 73: self.ima = "16.png" elif WiS < 78: self.ima = "17.png" elif WiS < 83: self.ima = "18.png" elif WiS < 88: self.ima = "19.png" elif WiS < 93: self.ima = "20.png" elif WiS < 98: self.ima = "21.png" elif WiS < 103: self.ima = "22.png" else: self.ima = "23.png" def show_barbs1(self): self.coord = CoordFind() vec_im = [] im = [] p = [] script_dir = os.path.dirname(os.path.abspath(__file__)) for i in range(0, self.HaM.shape[0]): self.barb_def(self.WiS[i]) p.append("{}{}".format('Red_Barbs\\', self.ima)) im.append(Image.open(os.path.join(script_dir, p[i]))) w, h = im[i].size im[i] = im[i].resize((int(w/2), int(h/2)), Image.ANTIALIAS) vec_im.append(ImageTk.PhotoImage(im[i].rotate(self.WiD[i]))) for i in range(0, self.HaM.shape[0]): if self.HaM[i] == 0: self.coord.find_px(self.Lat[i], self.Lon[i]) x = self.coord.LonPx y = self.coord.LatPx self.BrbImR[i] = self.cv.create_image(x, y, image = vec_im[i]) while True: for i in range(0, self.HaM.shape[0]): self.cv.itemconfigure(self.BrbImR[i], state = tk.NORMAL) self.shoRedBut.configure(text = "Showing H1") yield def show_barbs2(self): self.coord = CoordFind() vec_im = [] im = [] p = [] script_dir = os.path.dirname(os.path.abspath(__file__)) for i in range(0, self.HaM.shape[0]): self.barb_def(self.WiS[i]) p.append("{}{}".format('Green_Barbs\\', self.ima)) im.append(Image.open(os.path.join(script_dir, p[i]))) w, h = im[i].size im[i] = im[i].resize((int(w/2), int(h/2)), Image.ANTIALIAS) vec_im.append(ImageTk.PhotoImage(im[i].rotate(self.WiD[i]))) for i in range(0, self.HaM.shape[0]): if self.HaM[i] == 1: self.coord.find_px(self.Lat[i], self.Lon[i]) x = self.coord.LonPx y = self.coord.LatPx self.BrbImG[i] = self.cv.create_image(x, y, image = vec_im[i]) while True: for i in range(0, self.HaM.shape[0]): self.cv.itemconfigure(self.BrbImG[i], state = tk.NORMAL) self.shoGrnBut.configure(text = "Showing H2") yield def show_barbs3(self): self.coord = CoordFind() vec_im = [] im = [] p = [] script_dir = os.path.dirname(os.path.abspath(__file__)) for i in range(0, self.HaM.shape[0]): self.barb_def(self.WiS[i]) p.append("{}{}".format('Blue_Barbs\\', self.ima)) im.append(Image.open(os.path.join(script_dir, p[i]))) w, h = im[i].size im[i] = im[i].resize((int(w/2), int(h/2)), Image.ANTIALIAS) vec_im.append(ImageTk.PhotoImage(im[i].rotate(self.WiD[i]))) for i in range(0, self.HaM.shape[0]): if self.HaM[i] == 2: self.coord.find_px(self.Lat[i], self.Lon[i]) x = self.coord.LonPx y = self.coord.LatPx self.BrbImB[i] = self.cv.create_image(x, y, image = vec_im[i]) while True: for i in range(0, self.HaM.shape[0]): self.cv.itemconfigure(self.BrbImB[i], state = tk.NORMAL) self.shoBluBut.configure(text = "Showing H3") yield if __name__ == "__main__": root = tk.Tk() backmap = "Map.png" photo = ImageTk.PhotoImage(file = backmap) width = photo.width() height = photo.height() LatN = 69.5 LatS = -69.3 LonE = 148.9 LonW = 1.0 LatLc = (LatS - LatN)/height LonLc = (LonE - LonW)/width app = PlottingGUI(root) root.mainloop() But this ended up having a new problem. One set of coloured arrows is showing at a time but when I click the button to display another set it goes "Python stopped working because of some error" and then the shell restarts. Don't know what's the prob though.
PyQt dynamic stopwatch timer is slow because of slow updates
I am creating a "stopwatch" for a competition. A participants starts doing something, i star the program, and the participant can see his own placement which is updated dynamically with the watch. I have a fully functional code below: import sys from PyQt4 import QtGui, QtCore class Main(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) self.ms = 0 self.s = 0 self.m = 0 self.data_list = { "asd": "00:02:01", "bsd": "00:07:01", "csd": "00:01:01", "rrsd": "00:04:01", "fghsd": "00:01:41", "tzu": "00:09:01", "azud": "00:02:01", "cvb": "00:01:41", "jkl": "00:01:06", "aertt": "00:11:01" } self.next_comp = "" self.timer_state = False self.table_rows = 9 self.table_cols = 3 self.participants_above = 6 self.initUI() def initUI(self): centralwidget = QtGui.QWidget(self) self.lcd = QtGui.QLCDNumber(self) time = "{0:02d}:{1:02d}:{2:02d}".format(self.m, self.s, self.ms) self.lcd.setDigitCount(len(time)) self.lcd.display(time) self.timer = QtCore.QTimer(self) self.timer.timeout.connect(self.Time) self.start = QtGui.QPushButton("Start/Stop", self) self.start.clicked.connect(self.Start) self.reset = QtGui.QPushButton("Reset", self) self.reset.clicked.connect(self.Reset) self.le_name = QtGui.QLineEdit() self.table = QtGui.QTableWidget() self.table.setStyleSheet('QTableWidget { font-size: 24pt; padding: 10px; }') self.table.setRowCount(self.table_rows) self.table.setColumnCount(self.table_cols) self.table.setShowGrid(False) self.table.verticalHeader().setDefaultSectionSize(60) self.table.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch) self.table.verticalHeader().setVisible(False) self.table.horizontalHeader().setVisible(False) self.update_table() grid = QtGui.QGridLayout() grid.addWidget(self.start, 1, 0) grid.addWidget(self.reset, 1, 2) grid.addWidget(self.lcd, 2, 0, 1, 3) grid.addWidget(self.le_name, 3, 0, 1, 3) grid.addWidget(self.table, 4, 0, 1, 3) grid.setRowMinimumHeight(2, 100) centralwidget.setLayout(grid) self.setCentralWidget(centralwidget) # ---------Window settings -------------------------------- self.setGeometry(300, 300, 380, 370) # self.showFullScreen() def update_table(self, new_entry=""): local_data = self.data_list local_data.update(new_entry) local_data = [(v, k) for k, v in local_data.items()] local_data.sort(reverse=True) if new_entry: pos = local_data.index(tuple([(v, k) for k, v in new_entry.items()])[0]) else: pos = len(local_data) - 1 local_data = [(i, k) for i, k in enumerate(local_data)] if pos > self.participants_above: local_data = local_data[pos - self.participants_above:] for i, j in enumerate(local_data): self.a = QtGui.QTableWidgetItem(str(j[0] + 1)) self.a.setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignRight) self.table.setItem(i, 0, self.a) if new_entry and j[1] == tuple([(v, k) for k, v in new_entry.items()])[0]: self.table.item(i, 0).setBackground(QtGui.QColor("red")) self.a = QtGui.QTableWidgetItem(j[1][0]) self.a.setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignCenter) self.table.setItem(i, 1, self.a) if new_entry and j[1] == tuple([(v, k) for k, v in new_entry.items()])[0]: self.table.item(i, 1).setBackground(QtGui.QColor("red")) self.a = QtGui.QTableWidgetItem(j[1][1]) self.a.setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignLeft) self.table.setItem(i, 2, self.a) if new_entry and j[1] == tuple([(v, k) for k, v in new_entry.items()])[0]: self.table.item(i, 2).setBackground(QtGui.QColor("red")) def clear_table(self): for i in range(self.table_rows): for j in range(self.table_cols): self.table.setItem(i, j, QtGui.QTableWidgetItem("")) def Reset(self): self.timer.stop() self.clear_table() self.update_table() self.timer_state = False self.s = 0 self.m = 0 self.ms = 0 time = "{0:02d}:{1:02d}:{2:02d}".format(self.m, self.s, self.ms) self.lcd.setDigitCount(len(time)) self.lcd.display(time) def Start(self): if not self.timer_state: self.timer_state = True self.timer.start(10) else: self.timer_state = False self.timer.stop() def Time(self): if self.ms < 99: self.ms += 1 else: if self.s < 59: self.ms = 0 self.s += 1 elif self.s == 59 and self.m < 99: self.m += 1 self.ms = 0 self.s = 0 else: self.timer.stop() time = "{0:02d}:{1:02d}:{2:02d}".format(self.m, self.s, self.ms) self.update_table({self.le_name.text(): time}) self.lcd.setDigitCount(len(time)) self.lcd.display(time) app = QtGui.QApplication(sys.argv) main = Main() main.show() sys.exit(app.exec_()) As you can see the timer points to the Time function, and fires it every milisec. Inside the timer i update the list, so the participant and the viewers can see his placement all the time. The problem is that the timer is slower with every participant. I assume its because the computer is slow, and cant update the graphical table this fast, however i am struggling to come up with a better idea to make the clock work as a real clock, and maintain the dynamic update of the list as well. Any help would be appreciated!