How to print the results of an input variable inside a function - function

here is my code, the input variable is map1 where the user is promoted to enter a filepath, I want to print('map saved to', map1) after the user inputs the location, but I am getting the error NameError: name 'map1' is not defined. The variable is defined and is assigned a value when the user puts an input. Why won't it print?
def question2(two):
map1 = input('where do you want to save the map? please enter filepath with image type e.g C:/map.jpg: ')
fig, ax = plt.subplots(figsize = (15,12))
filtered_buildings.plot(ax = ax, color = 'red', edgecolor = 'black',)
Highway.plot(ax = ax, color = 'black')
Tunnel.plot(ax = ax, color = 'green', alpha = 0.5, edgecolor = 'black',)
Tunnel_buffer.plot(ax = ax, facecolor='none', edgecolor = 'black',)
ctx.add_basemap(ax, source=ctx.providers.OpenStreetMap.Mapnik)
plt.title('Filtered Buildings')
plt.savefig(fname=map1, dpi=300)
if __name__ == '__main__':
do_again = 'start_string'
while not do_again in ['yes', 'y', 'Yes', 'No', 'n', 'no']:
do_again = input("Would you like to save the final map? (y/n)? ").lower()
if do_again == 'yes' or do_again == 'y' or do_again == 'Yes':
print('Saving Map...')
print('map saved to', map1)
question2()

The print statements
print('Saving Map...')
print('map saved to', map1)
Should be directly after the plt.savefig(fname=map1, dpi=300) and before if __name__ == '__main__':
Correct code is:
def question2():
map1 = input('where do you want to save the map? please enter filepath with image type e.g C:/map.jpg: ')
fig, ax = plt.subplots(figsize = (15,12))
filtered_buildings.plot(ax = ax, color = 'red', edgecolor = 'black',)
Highway.plot(ax = ax, color = 'black')
Tunnel.plot(ax = ax, color = 'green', alpha = 0.5, edgecolor = 'black',)
Tunnel_buffer.plot(ax = ax, facecolor='none', edgecolor = 'black',)
ctx.add_basemap(ax, source=ctx.providers.OpenStreetMap.Mapnik)
plt.title('Filtered Buildings')
plt.savefig(fname=map1, dpi=300)
print('Saving Map...')
print('map saved to', map1)
if __name__ == '__main__':
do_again = 'start_string'
while not do_again in ['yes', 'y', 'Yes', 'No', 'n', 'no']:
do_again = input("Would you like to save the final map? (y/n)? ").lower()
if do_again == 'yes' or do_again == 'y' or do_again == 'Yes':
question2()

Related

How do I fix this error when creating a tkinter button?

from tkinter import *
import pickle
from tkinter import messagebox
from tkinter import ttk
Id = 0
Idx800 = 0
Idx900 = 0
class Vozac():
def __init__(self,ime,prezime):
self.Ime = ime
self.Prezime = prezime
global Id
self.Id = Id
Id = Id + 1
self.termini = []
def dodajTermin(self,termin):
self.termini.append(termin)
def obrisiTermin(self,termin):
self.termini.remove(termin)
def dodajVozaca():
new_window = Toplevel()
new_window.geometry("400x200")
label1 = Label(new_window,text="Ime:", font=('Arial',30))
label1.place(x=50,y=0)
global entry1
entry1 = Entry(new_window, font=('Arial',30))
entry1.place(x=180,y=0)
label2 = Label(new_window, text="Prezime:", font=('Arial', 30))
label2.place(x=0, y=50)
global entry2
entry2 = Entry(new_window, font=('Arial', 30))
entry2.place(x=180, y=50)
submit_button = Button(new_window, text="Dodaj vozaca", font=('Arial', 25), command=lambda: vozacHandler(entry1, entry2, new_window))
submit_button.place(x=100,y=100)
def vozacHandler(entry1, entry2, new_window):
ime = entry1.get()
prezime = entry2.get()
new_window.destroy()
zastavica = 1
dodajVozacaNaGUI(ime, prezime, zastavica)
def dodajVozacaNaGUI(ime, prezime, zastavica):
vozac = Vozac(ime, prezime)
button = Button(window, text=ime+" "+prezime, command=lambda: prikaziTermine(vozac, button))
if vozac.Id < 25:
button.grid(row=vozac.Id, column = 0)
if vozac.Id < 50 and vozac.Id >= 25:
button.grid(row=vozac.Id-25, column = 1)
if vozac.Id < 75 and vozac.Id >= 50:
button.grid(row=vozac.Id-50, column = 2)
if vozac.Id < 100 and vozac.Id >= 75:
button.grid(row=vozac.Id-75, column = 3)
if zastavica:
spremiVozaca(vozac)
def spremiVozaca(vozac):
pickle_out = open("vozaci.pickle", "ab")
pickle.dump(vozac, pickle_out)
pickle_out.close()
def on_closing():
if messagebox.askokcancel("Izlazak", "Da li zelite izaci?"):
window.destroy()
def prikaziTermine(vozac, button1):
new_window = Toplevel()
new_window.geometry("400x300")
pickle_in = open("vozaci.pickle", "rb")
while 1:
try:
vozac1 = pickle.load(pickle_in)
if vozac1.Ime == vozac.Ime and vozac1.Prezime == vozac.Prezime:
for i in range(len(vozac1.termini)):
label = Label(new_window, text=vozac1.termini[i], font=('Arial', 25))
label.place(x=0, y=0 + 50 * i)
except:
EOFError
break
button = Button(new_window, text="Obrisi vozaca", font=('Arial', 25), command=lambda: obrisiVozaca(vozac, button1, new_window))
button.place(x=100, y=220)
def obrisiVozaca(vozac, button, new_window):
new_window.destroy()
button.destroy()
pickle_in = open("vozaci.pickle", "rb")
pickle_out = open("vozaci1.pickle", "ab")
while 1:
try:
vozac1 = pickle.load(pickle_in)
if vozac.Ime == vozac1.Ime and vozac.Prezime == vozac1.Prezime:
global Id
Id = Id-1
for i in range(100):
vozac2 = pickle.load(pickle_in)
vozac2.Id = vozac2.Id-1
print(vozac2.Id)
print(vozac2.Ime)
pickle.dump(vozac2, pickle_out)
else:
pickle.dump(vozac1, pickle_out)
except:
EOFError
pickle_out.close()
break
pickle_out1 = open("vozaci.pickle", "w").close()
pickle_in1 = open("vozaci1.pickle", "rb")
pickle_out2 = open("vozaci.pickle", "ab")
while 1:
try:
vozac2 = pickle.load(pickle_in1)
pickle.dump(vozac2, pickle_out2)
except:
EOFError
pickle_out2.close()
break
pickle_out3 = open("vozaci1.pickle", "w").close()
def dodajTermin():
new_window = Toplevel()
new_window.geometry("400x200")
linija = notebook.tab(notebook.select(), "text")
label1 = Label(new_window, text="Termin:", font=('Arial', 30))
label1.place(x=0, y=0)
global entry
entry = Entry(new_window, font=('Arial', 30))
entry.place(x=150, y=0)
submit_button = Button(new_window, text="Dodaj termin", font=('Arial', 25), command=lambda: terminHandler(entry, new_window, linija))
submit_button.place(x=100, y=100)
def terminHandler(entry, new_window, linija):
termin = entry.get()
new_window.destroy()
zastavica = 1
dodajTerminNaGUI(termin, linija, zastavica)
def dodajTerminNaGUI(termin, linija, zastavica):
if linija == "x800":
global Idx800
button1 = Button(tab1, text=termin, command=lambda: dodajTerminVozacu(termin, button1))
button1.place(x=0,y=0+50*Idx800)
Idx800 = Idx800+1
if linija == "x900":
global Idx900
button2 = Button(tab2, text=termin, command=lambda: dodajTerminVozacu(termin, button2))
button2.place(x=0,y=0+50*Idx900)
Idx900 = Idx900+1
if zastavica:
spremiTermin(linija, termin)
def spremiTermin(linija, termin):
if linija == "x800":
pickle_out = open("terminix800.pickle", "ab")
pickle.dump(termin, pickle_out)
pickle_out.close()
if linija == "x900":
pickle_out1 = open("terminix900.pickle", "ab")
pickle.dump(termin, pickle_out1)
pickle_out1.close()
def dodajTerminVozacu(termin, button):
new_window = Toplevel()
new_window.geometry("500x900")
pickle_in = open("vozaci.pickle", "rb")
i = 0
vozaci = []
while 1:
try:
vozaci.append(pickle.load(pickle_in))
button1 = Button(new_window, text=vozaci[i].Ime + " " + vozaci[i].Prezime, command=lambda: dodavanjeTermina(vozaci[i], termin, button, new_window))
if vozaci[i].Id < 25:
button1.grid(row=vozaci[i].Id, column=0)
if vozaci[i].Id < 50 and vozaci[i].Id >= 25:
button1.grid(row=vozaci[i].Id - 25, column=1)
if vozaci[i].Id < 75 and vozaci[i].Id >= 50:
button1.grid(row=vozaci[i].Id - 50, column=2)
if vozaci[i].Id < 100 and vozaci[i].Id >= 75:
button1.grid(row=vozaci[i].Id - 75, column=3)
i = i + 1
except:
EOFError
break
def dodavanjeTermina(vozac,termin, button, new_window):
#print(id)
pickle_in = open("vozaci.pickle", "rb")
pickle_out = open("vozaci1.pickle", "ab")
while 1:
try:
vozac1 = pickle.load(pickle_in)
if vozac1.Ime == vozac.Ime and vozac1.Prezime == vozac.Prezime:
vozac1.dodajTermin(termin)
pickle.dump(vozac1, pickle_out)
else:
pickle.dump(vozac1, pickle_out)
except:
EOFError
pickle_out.close()
break
pickle_in1 = open("vozaci.pickle", "w").close()
pickle_in2 = open("vozaci1.pickle", "rb")
pickle_out1 = open("vozaci.pickle", "ab")
while 1:
try:
vozac2 = pickle.load(pickle_in2)
pickle.dump(vozac2, pickle_out1)
except:
EOFError
pickle_out1.close()
break
pickle_out2 = open("vozaci1.pickle", "w").close()
button.destroy()
#tu treba obrisati termin iz picklea
new_window.destroy()
if __name__ == '__main__':
window = Tk()
window.geometry("2000x1100")
menubar = Menu(window)
window.config(menu=menubar)
fileMenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="Opcije", menu=fileMenu)
fileMenu.add_command(label="Dodaj vozaca", command=dodajVozaca)
fileMenu.add_command(label="Dodaj termin", command=dodajTermin)
notebook = ttk.Notebook(window)
tab1 = Frame(notebook, width=1400, height=900, bg="red")
tab2 = Frame(notebook, width=1400, height=900, bg="blue")
notebook.add(tab1, text="x800")
notebook.add(tab2, text="x900")
notebook.place(x=500, y=0)
window.protocol("WM_DELETE_WINDOW", on_closing)
pickle_inx = open("vozaci.pickle", "rb")
while 1:
try:
vozac11 = pickle.load(pickle_inx)
dodajVozacaNaGUI(vozac11.Ime, vozac11.Prezime, 0)
except:
EOFError
break
pickle_in1x = open("terminix800.pickle", "rb")
while 1:
try:
termin = pickle.load(pickle_in1x)
dodajTerminNaGUI(termin, "x800", 0)
except:
EOFError
break
pickle_in2x = open("terminix900.pickle", "rb")
while 1:
try:
termin = pickle.load(pickle_in2x)
dodajTerminNaGUI(termin, "x900", 0)
except:
EOFError
break
window.mainloop()
Python says that I have list out of index error in line when I create a button (function-dodajTerminVozacu), I can't figure out why, I tried out printing data before its assigned to button and everything seems fine. Content of vozaci.pickle is 3 objects and every one of them includes: name, surname and id. Whenever I do pickle.load one object in series appears.

wanting to write a txt with Tkinter entry box

just trying to allow users to write in their name and email address for it to be then written into a text file. There are no error messages that pop up it's just, it isn't writing into the file. also, the message box isn't coming up with (+ aname + '\n' + full email + '\n') it just comes up with the message. Cheers
import tkinter as tk #shortening tkinter
import tkinter.messagebox as box
import csv
from tkinter import *
def store_customers():
aname = name.get()
aemail = email.get()
aemailaddress = emailaddress.get()
fullemail = aemail + aemailaddress
print(fullemail)
if (name == "" or email == ""):
print('Error')
messagebox.showerror('error',"their was some issur with your information")
email.set('')
name.set('')
else:
result = messagebox.askquestion('question', 'Your about to enter yor information \n' + aname + '\n' + fullemail + '\n' )
if (result == 'yes'):
print('here')
with open ('customersdata.txt', 'a') as csvfile:
writer = csv.writer(csvfile)
writer.writerow([aname, fullemail])
csvfile.close()
else:
name.set('')
email.set('')
name = StringVar()
email = StringVar()
emailaddress = StringVar()
name = tk.Entry(frame4, text="", bg = '#F0EAD6', font=('Arial',24) )
name.place(x= 400, y = 600)
email = tk.Entry(frame4, text="", bg = '#F0EAD6', font=('Arial',24) )
email.place(x= 400, y = 660)
list1 = ['#yahoo.com','#bing.com','#jpc.vic.edu.au', '#gmail.com', '#hotmail.com' ]
emailaddres= OptionMenu(frame4,emailaddress,*list1)
emailaddres.config(height = 2 )
emailaddress.set('#***.***.edu.au')
emailaddres.place(x= 685, y= 660)
storebtn = tk.Button(frame4, text = 'complete', bg= '#F0EAD6', font=('Arial',24), command = store_customers)
storebtn.place (x = 430, y= 700)
tk.Label(frame4, text= "Your name", bg= '#F0EAD6', font=('Arial',24)).place(x = 260, y = 600)
tk.Label(frame4, text= "email address", bg= '#F0EAD6', font=('Arial',24)).place(x = 240, y = 660)
frame4.mainloop()
Code with Tkinter.
import csv
import tkinter
import tkinter.messagebox
def save():
nome_to_save = namevalue.get()
email_to_save = emailvalue.get()
if len(nome_to_save) == 0 or len(email_to_save) == 0:
tkinter.messagebox.showinfo('Error', 'You need to enter name and e-mail!')
else:
with open('customersdata.csv', 'a', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow([nome_to_save, email_to_save])
csvfile.close()
tkinter.messagebox.showinfo('Success', f'Information of {nome_to_save} saved!')
window = tkinter.Tk()
window.title("Write CSV")
namevalue = tkinter.StringVar()
emailvalue = tkinter.StringVar()
tkinter.Label(window, text = "Name").grid(row = 0)
name = tkinter.Entry(window, textvariable=namevalue).grid(row = 0, column = 1)
tkinter.Label(window, text = "E-mail").grid(row = 1)
email = tkinter.Entry(window, textvariable=emailvalue).grid(row = 1, column = 1)
tkinter.Button(window, text="Save", command = save).grid(row = 2)
tkinter.mainloop()
You probably receive some error, right?
You have imported tkinter.messagebox as box.
So replace messagebox.showerror and messagebox.askquestion with box.showerror and box.askquestion
PS: I am new here, so I cannot comment. Sorry!
This code can help you.
import csv
def store_customers(name, email):
if name == "" or email == "":
print('Error, i need name and email')
else:
with open('customersdata.csv', 'a', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow([name, email])
csvfile.close()
#store_customers('', '')
store_customers('Diego', 'diego#false.io')
store_customers('Ana Maria', 'ana.maria#myemail.io')
store_customers('Julia Neau', 'jneau#cool.io')

PyGame surface locked during blit [duplicate]

I am trying to draw text to a screen in a space above a bunch of rects that are all in the 2d array square. When i try and draw text to the screen it says that "Surfaces must not be locked during blit."
I have tried unlocking, it makes no difference.
import sys, time, random, pygame
from pygame import *
from time import time,sleep
pygame.init()
global isDragging, inDrag, rightDrag, lastDrag, inDragRight, mouseX,mouseY, borderHeight
isDragging = False
isAuto = False
inDrag= False
inDragRight = False
isFilling = False
done = False
lastDrag = None
rightDrag = None
tickTime = 300
font = pygame.font.SysFont(None, 12,False,False)
dragDelay = 2
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
PINK = ( 255, 150, 200)
BLUE = ( 0, 0, 255)
RED = GREEN
width, height, margin = 100, 100, 1
noWidth, noHeight = 6,6
speed = [2, 2]
borderHeight = 50
size = (width*noWidth,height*noHeight + borderHeight)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("PieStone")
clock = pygame.time.Clock()
pixArray = pygame.PixelArray(screen)
font = pygame.font.SysFont("monospace", 15)
word = font.render("test", 1, (0, 0, 0))
class Null:
pass
square = [[Null() for i in range(noHeight)]for i in range(noWidth)]
for d1 in range(noWidth):
for d2 in range(noHeight):
square[d1][d2].man = False
square[d1][d2].visits = 0
square[d1][d2].colour = BLACK
square[d1][d2].margin = 1
a = 1
i = 1
def text(word,size,pos1,pos2,pos3):
word = font.render(str(word),size,(pos1,pos2,pos3))
return word
def colide(obj,mouseX,mouseY):
if obj.collidepoint(mouseX,mouseY) == 1:
return True
else:
return False
def click(mouseX,mouseY):
#rint("left")
global inDrag,lastDrag
for d1 in range(noWidth):
for d2 in range(noHeight):
if colide(square[d1][d2].rect,mouseX,mouseY):
square[d1][d2].man = True
#print("square",d1,d2,"has been clicked")
try:
if square[d1][d2] != lastDrag:
inDrag = True
lastDrag = square[d1][d2]
else:
inDrag = False
except UnboundLocalError:
print("error")
lastDrag = square[d1][d2]
#print(inDrag)
if square[d1][d2].margin == 0 and inDrag:
square[d1][d2].margin = 1
square[d1][d2].visits = square[d1][d2].visits + 1
elif square[d1][d2].margin == 1 and inDrag:
square[d1][d2].margin = 0
square[d1][d2].visits = square[d1][d2].visits + 1
break
'''if square[d1][d2].visits >= 5 and square[d1][d2].colour == BLACK:
square[d1][d2].visits = 0
square[d1][d2].colour = RED
elif square[d1][d2].visits >= 5 and square[d1][d2].colour == RED:
square[d1][d2].visits = 0
square[d1][d2].colour = BLACK'''
def rightClick(mouseX,mouseY):
#print("right")
global inDragRight, lastRight
for d1 in range(noWidth):
for d2 in range(noHeight):
if colide(square[d1][d2].rect,mouseX,mouseY):
square[d1][d2].man = True
#print("colide")
try:
if square[d1][d2] != lastRight:
inDragRight = True
lastRight = square[d1][d2]
else:
inDragRight = False
except:
print("error")
lastRight = square[d1][d2]
#print(inDragRight)
if square[d1][d2].colour == RED and inDragRight:
square[d1][d2].colour = BLACK
#print("black")
elif square[d1][d2].colour == BLACK and inDragRight:
square[d1][d2].colour = RED
#print("red")
break
while not done:
screen.blit(word, (0, 0))
(mouseX,mouseY) = pygame.mouse.get_pos()
#print(str(mouseX)+",",mouseY)
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
elif event.type == pygame.MOUSEBUTTONDOWN:
#print(mouseX,mouseY)
if pygame.mouse.get_pressed()[0] == 1:
isDragging = True
if pygame.mouse.get_pressed()[2] == 1:
isFilling = True
elif pygame.mouse.get_pressed()[1] == 1:
isAuto = True
#print(pygame.mouse.get_pressed())
elif event.type == pygame.MOUSEBUTTONUP:
#print("up")
isDragging = False
isFilling = False
lastDrag = None
lastRight = False
if pygame.mouse.get_pressed()[0] == 1:
isDragging = True
if pygame.mouse.get_pressed()[2] == 1:
isFilling = True
if isAuto:
rnd1 = random.randint(0,1)
if rnd1 == 1:
isDragging = True
isFilling = False
else:
isDragging = False
isFilling = True
(mouseX,mouseY) = (random.randint(0,width*noWidth),random.randint(0,height*noHeight)+borderHeight)
#print(mouseX,mouseY)
if isDragging:
click(mouseX,mouseY)
if isFilling:
rightClick(mouseX,mouseY)
screen.fill(WHITE)
# --- Game logic should go here
i = 0
for d1 in range(noWidth):
if noHeight % 2 == 0:
'''if i == 0:
i = 1
else:
i = 0'''
for d2 in range(noHeight):
#if i % a == 0:
try:
if i == 0:
pass
elif i == 1:
pass
except AttributeError:
print("AttributeError")
square[d1][d2].margin = random.randint(0,1)
#print(square[d1][d2].visits)
square[d1][d2].rect = pygame.draw.rect(screen, square[d1][d2].colour, [(d1*width), ((d2*height)+borderHeight),width,(height)],square[d1][d2].margin)
#print("d1*width:",d1*width,"d2*height:",d2*height,"d1*width+width:",d1*width+width,"d2*height+height:",d2*height+height)
pygame.display.flip()
clock.tick(tickTime)
# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()
You're using a PixelArray:
pixArray = pygame.PixelArray(screen)
But using a PixelArray locks your Surface, as stated in the documentation:
During its lifetime, the PixelArray locks the surface, thus you explicitly have to delete it once its not used anymore and the surface should perform operations in the same scope.
Just remove the line, since you're not using it anyway.

doing a search of the database python/flask no sql

I am trying to get a search function working. I have a database using excel and would like to be able to search it while on the go. I am stuck trying to get the search form working. Below is the code in python for the form:
from forms import ComicSearchForm
#app.route('/make_search', methods=['GET', 'POST'])
def search():
search = ComicSearchForm(request.form)
if request.method == 'GET, POST':
return search_results(result)
return render_template('search.html', form=search)
#app.route('/search')
# #login required
def search_results(result):
bob = create_bob('*', '*', '*', '*', '*', '*')
bobby = []
current_page = request.args.get('page', 1, type=int)
per_page = 10
end = (current_page * per_page) + 1
if end > len(bob):
end = len(bob)
start = ((current_page - 1) * per_page) + 1
sort_bob = sorted(bob, key=lambda v: (v.issue_type, v.publisher, v.sort, v.character, v.volume, v.issues,
v.publication_date))
if datetime.strptime(sort_bob[0][7], '%B, %Y') >= datetime.now():
sort_bob = sorted(sort_bob, key=lambda v: (v.publication_date, '%B, %Y'))
for result in bob[start:end]:
if result.bob.series_title == str.find(''):
bobby.append(result)
next = str(current_page + 1) if end < len(bob) else '0'
prev = str(current_page - 1)
if not result:
flash('No results found!')
return redirect('make_search')
else:
# display results
return render_template('search.html', bobby=bobby, header=original_header, next=next, prev=prev)
Here is the form:
from wtforms import Form, StringField, SelectField
class ComicSearchForm(Form):
choices = [('Series Title', 'Series Title'),
('Author', 'Author'),
('Artist', 'Artist'),
('Publisher', 'Publisher'),
('Publication Date', 'Publication Date')]
select = SelectField('Search for comics:', choices=choices)
search = StringField('')
I am stuck trying to figure out:
for result in bob[start:end]:
if result.bob.series_title == str.find(''):
bobby.append(result)
This is where i am currently think this needs work. I would love some ideas of where i need to go to make this work.
Thanks,
Zach

set “child2, mygrid_2” values into “MyPanel, myGrid”

i want to set values into myGrid Parent(MyPanel) from child2, but failed to do so, Please help and suggest as i m new in programming, Thanks in advance
import wx
import wx.grid
import MySQLdb
########################################################################
class MyPanel(wx.Panel):
#----------------------------------------------------------------------
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.currentlySelectedCell = (0, 0)
self.parent = parent
self.myGrid = wx.grid.Grid(self)
self.myGrid.CreateGrid(8, 6)
self.myGrid.Bind(wx.EVT_CHAR, self.OnChar)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.myGrid, 1, wx.EXPAND)
self.SetSizer(sizer)
self.child1 = MyDialog1(self)
self.child2 = MyDialog2(self)
#------------------------------------------------------------------------
def OnChar(self, event):
pro = self.myGrid.GetCellValue(0, 0)
cnn = MySQLdb.connect("localhost", "root", "pass", "rms" )
cursor=cnn.cursor()
cursor.execute("SELECT product_name, supplier_name FROM products WHERE product_name LIKE '%"+pro+"%'")
rows=cursor.fetchall()
for i in range(len(rows)):
for j in range(0,2):
cell=rows[i]
self.child1.grid_1.SetCellValue(i,j,str(cell[j]))
cnn.commit()
cnn.close()
event.Skip()
self.child1.Show()
########################################################################
class MyDialog1(wx.Dialog):
def __init__ (self, parent1):
wx.Dialog.__init__(self, None, size=(350, 250), title="CHILD 1", style=wx.DEFAULT_DIALOG_STYLE)
wx.Dialog.CenterOnScreen(self)
self.parent = parent1
self.grid_1 = wx.grid.Grid(self)
self.but = wx.Button(self, -1, "Load")
self.Bind(wx.grid.EVT_GRID_SELECT_CELL, self.click, self.grid_1)
self.grid_1.CreateGrid(7, 2)
self.grid_1.SetColLabelValue(0, ("ProductName"))
self.grid_1.SetColSize(0, 150)
self.grid_1.SetColLabelValue(4, ("Supplier Name"))
self.grid_1.SetColSize(4, 165)
sizer_4 = wx.GridSizer(wx.FLEX_GROWMODE_ALL)
sizer_4.Add(self.grid_1, 1, wx.EXPAND, 0)
sizer_4.Add(self.but, 1, wx.CENTER, 0)
self.SetSizer(sizer_4)
self.child2 = MyDialog2(self)
#-----------------------------------------------------------------------
def click(self, event):
pro1 = self.grid_1.GetCellValue(0, 0)
cnn = MySQLdb.connect("localhost", "root", "pass", "rms" )
cursor=cnn.cursor()
cursor.execute("SELECT product_name, batch_no, qty, purchase_price, sale_price FROM purchase_item WHERE product_name LIKE '%"+pro1+"%'")
rows=cursor.fetchall()
for i in range(len(rows)):
for j in range(0,5):
cell = rows[i]
self.child2.grid_2.SetCellValue(i,j,str(cell[j]))
cnn.commit()
cnn.close()
event.Skip()
self.child2.Show()
########################################################################
class MyDialog2(wx.Dialog):
def __init__ (self, parent):
wx.Dialog.__init__(self, None, size=(650, 300), title="CHILD 2", style=wx.DEFAULT_DIALOG_STYLE)
wx.Dialog.CenterOnScreen(self)
self.parent = parent
self.grid_2 = wx.grid.Grid(self)
self.Bind(wx.grid.EVT_GRID_SELECT_CELL, self.click2, self.grid_2)
self.grid_2.CreateGrid(7, 5)
self.grid_2.SetColLabelValue(0, ("ProductName"))
self.grid_2.SetColSize(0, 150)
self.grid_2.SetColLabelValue(1, ("Batch No"))
self.grid_2.SetColSize(1, 80)
self.grid_2.SetColLabelValue(2, ("Stock"))
self.grid_2.SetColSize(2, 80)
self.grid_2.SetColLabelValue(3, ("Purchase Rate"))
self.grid_2.SetColSize(3, 80)
self.grid_2.SetColLabelValue(4, ("Sale Rate"))
self.grid_2.SetColSize(4, 165)
sizer_4 = wx.GridSizer(wx.FLEX_GROWMODE_ALL)
sizer_4.Add(self.grid_2, 1, wx.EXPAND, 0)
self.SetSizer(sizer_4)
#----------------------------------------------------------------------
def click2(self, event):
for row in range(0,5):
for col in range(0,5):
val = self.grid_2.GetCellValue(0,5)
self.parent.myGrid.SetCellValue(str(val)) # I want to show this Cell
#Values in MyPanel Class myGrid value
event.Skip()
self.Destroy()
#self.Close()
Traceback here:
""" >>> Traceback (most recent call last):
File "/home/sunil/GuiTest/Grid_project_New.py", line 96, in click2
self.parent.myGrid.SetCellValue(str(val)) # I want to show this Cell Values in MyPanel Class myGrid value
AttributeError: 'MyDialog1' object has no attribute 'myGrid' """
rest of code:
########################################################################
class MyFrame(wx.Frame):
#----------------------------------------------------------------------
def __init__(self):
wx.Frame.__init__(self, parent=None)
panel = MyPanel(self)
self.Show()
#----------------------------------------------------------------------
if __name__ == "__main__":
app = wx.App(False)
frame = MyFrame()
app.MainLoop()