deepak
2014-03-12 17:08:50 UTC
I am ne to python GUi, I have built a cust frame by inheriting the Frame ,
the code is as follows :
from Tkinter import *
from logging import exception
import tkFileDialog
import pickle
import os.path
STATION_NAME, TARGET_NAME, HOST_NAME, TARGET_IP, HOST_IP, EXCEL_FILE =
range(6)
class NAddStation(Frame):
def __init__(self, parent=None):
Frame.__init__(self, parent)
self.pack(side=TOP, expand=YES, fill=BOTH)
self.tempVar = []
# Label Area
self.labels = ["Station Name :", "Target Name :", "Host Name
:", "Target's IP :", "Host's IP :",
"Excel File :"]
self.REMOVE =1
self.ADD = 2
self.UPDATE = 3
# Entry Area
self.Entry_Target_Name = None
self.Entry_Host_Name = None
self.Entry_Target_IP = None
self.Entry_Host_IP = None
self.Entry_Station_Name = None
self.Entry_File_Path = None
#Misc
self.File_Browse_Button = None
self.Add_Button = None
self.Cancel_Button = None
self.createWindow()
def openFileBrowser(self):
filepath = tkFileDialog.askopenfilename()
self.Entry_File_Path.insert(0, filepath)
def validate(self):
print("Adding Data....")
self.Store_Station()
def Remove_Station(self,key):
if os.path.isfile('Station-pickle'):
dbfile = open('Station-pickle', 'rb')
db = pickle.load(dbfile)
dbfile.close()
db.__delitem__(key)
dbfile = open('Station-pickle', 'wb')
pickle.dump(db, dbfile)
dbfile.close()
def returnStationName(self):
return self.tempVar[0].get()
def Store_Station(self):
fl={}
rc={}
fl['SN']= self.tempVar[0].get()
fl['HN']= self.tempVar[1].get()
fl['HP']= self.tempVar[2].get()
fl['TN']= self.tempVar[3].get()
fl['TP']= self.tempVar[4].get()
fl['XL']= self.tempVar[5].get()
station_name = self.tempVar[0].get()
rc[station_name]= fl
if not os.path.isfile('Station-pickle'):
print ("Creating File")
dbfile = open('Station-pickle', 'wb') # use
binary mode files in 3.X
pickle.dump(rc, dbfile) # data is
bytes, not str
else:
print ("Appending File")
# --------
dbfile = open('Station-pickle', 'rb')
db = pickle.load(dbfile)
dbfile.close()
db[station_name] = fl
dbfile = open('Station-pickle', 'wb')
pickle.dump(db, dbfile)
dbfile.close()
dbfile.close()
def Load_Station(self, key_value):
dbfile = open('Station-pickle', 'rb') # use binary
mode files in 3.X
db = pickle.load(dbfile)
for key in db:
if key == key_value:
print("STATION_NAME :" + db[key]['SN'])
print("HOST_NAME :" + db[key]['HN'])
print("HOST_IP :" + db[key]['HP'])
print("TARGET_NAME :" + db[key]['TN'])
print("TARGENT_IP :" + db[key]['TP'])
print("FILE_NAME :" + db[key]['XL'])
return ("STATION_NAME :" + db[key]['SN'] +"\n" +
"HOST_NAME :" + db[key]['HN'] + "\n" + "HOST_IP :" +
db[key]['HP'] + "\n" + "TARGET_NAME :" + db[key]['TN'] + "\n" +
"TARGENT_IP :" + db[key]['TP'] + "\n" + "FILE_NAME :" +
db[key]['XL'])
print "No Station with Name " + key_value
dbfile.close()
def createWindow(self):
# Station Entry
Label(self, text=self.labels[STATION_NAME]).grid(row=0,
column=0)
self.Entry_Station_Name = Entry(self, width=20)
self.tempVar.append(self.Entry_Station_Name)
self.Entry_Station_Name.grid(row=0, column=1)
# Host Entry
Label(self, text=self.labels[HOST_NAME]).grid(row=1, column=0)
self.Entry_Host_Name = Entry(self, width=20)
self.tempVar.append(self.Entry_Host_Name)
self.Entry_Host_Name.grid(row=1, column=1)
Label(self, text=self.labels[HOST_IP]).grid(row=1, column=2)
self.Entry_Host_IP = Entry(self, width=20)
self.tempVar.append(self.Entry_Host_IP)
self.Entry_Host_IP.grid(row=1, column=3)
# Target Entry
Label(self, text=self.labels[TARGET_NAME]).grid(row=2, column=0)
self.Entry_Target_Name = Entry(self, width=20)
self.tempVar.append(self.Entry_Target_Name)
self.Entry_Target_Name.grid(row=2, column=1)
Label(self, text=self.labels[TARGET_IP]).grid(row=2, column=2)
self.Entry_Target_IP = Entry(self, width=20)
self.tempVar.append(self.Entry_Target_IP)
self.Entry_Target_IP.grid(row=2, column=3)
#Browser Button
Label(self, text=self.labels[EXCEL_FILE]).grid(row=3, column=0)
self.Entry_File_Path = Entry(self, width=50)
self.tempVar.append(self.Entry_File_Path)
self.Entry_File_Path.grid(row=3, column=1)
self.File_Browse_Button = Button(self, text="Browse",
command=self.openFileBrowser, width=10,justify=CENTER).grid(row=3, column=3)
Button(self, text="Add", command=(lambda : self.validate()),
width=10,justify=CENTER).grid(row=4, column=1)
Button(self, text="Cancel", command=
self.winfo_toplevel().destroy, width=10,justify=CENTER).grid(row=4,
column=2)
self.Entry_Station_Name.focus()
**Now I want to use the above mentioned Custom Frame in Main app , when i
ckick on AddStation from menu file the custome Frame pops up , I can add
the data but when i click on ok , i want the data to apear on the textArea ,
represented by Self.Entity2 in the following code:**
from Tkconstants import LEFT, BOTTOM, X, TOP, RIGHT, ACTIVE, Y
from Tkinter import Tk, Frame, Menu, END, Label, YES, BOTH, Entry,
StringVar, Toplevel
import Tkinter
import sys
from make_db_pickle import *
class SimpleApp(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.pack(expand=YES, fill=BOTH)
self.master.title('GUI')
self.initialize(parent)
self.TargetName = None
self.HostName = None
self.eHostNameEntry =None
self.sbar = None
self.AddWidget = None
def CancelButtonPressed(self, widget):
# print "Cancel Button Pressed"
widget.destroy()
def AddEntryToListBox(self,entry):
self.entry1.insert(END, entry)
def enter(event,entry,widget):
event.OkButtonPressed(entry,widget)
def OkButtonPressed(self,entry,widget):
print "Ok bution pressed"
self.AddEntryToListBox(str(entry.get()).upper())
widget.destroy()
def runCommand(self, selection): # redefine me
lower
self.entry2.insert('1.0',"The following Station was selected " +
selection)
self.entry3.insert('1.0',"The following Station was selected " +
selection)
self.entry4.insert('1.0',"The following Station was selected " +
selection)
print('You selected:', selection)
def handleList(self, event):
index = self.entry1.curselection() # on list
double-click
label = self.entry1.get(index) # fetch
selection text
self.runCommand(label) # and call
action here
def initialize(self, parent):
menubar = Menu(self.parent)
self.parent.config(menu=menubar)
self.sbar = Tkinter.Scrollbar(self)
fileMenu = Menu(menubar, tearoff = False)
fileMenu.add_command(label="Add Station",
command=self.AddNewStation)
fileMenu.add_command(label="Delete Station",
command=self.onExit)
fileMenu.add_separator()
fileMenu.add_command(label="Exit", command=self.onExit)
menubar.add_cascade(label="File", menu=fileMenu)
self.grid()
self.entry1 = Tkinter.Listbox(self, height=24, yscrollcommand=1,
bg="white")
# --------------------------
self.sbar = Tkinter.Scrollbar(self)
self.sbar.config(command=self.entry1.yview) #
xlink sbar and list
self.entry1.config(yscrollcommand=self.sbar.set) #
move one moves other
self.entry1.pack(side=LEFT, expand=YES, fill=BOTH) # list
clipped first
# pos = 0
#list.config(selectmode=SINGLE, setgrid=1) #
select,resize modes
self.entry1.bind('<Double-1>', self.handleList) # set
event handler
# --------------------------
# for i in acts:
# self.entry1.insert(END, i)
# self.entry1 = Tkinter.Text(self)
self.entry1.grid(column=0, row=0, sticky='EW')
self.entry2 = Tkinter.Text(self)
self.entry2.grid(column=1, row=0, sticky='EW', padx=1, pady=1)
self.entry3 = Tkinter.Text(self)
self.entry3.grid(column=0, row=1, sticky='EW', padx=1, pady=1)
self.entry4 = Tkinter.Text(self)
self.entry4.grid(column=1, row=1, sticky='EW', padx=1, pady=1)
def onExit(self):
sys.exit()
def AddNewStation(self):
n = Toplevel(root)
n.title("Add Station")
self.AddWidget = NAddStation(n)
n.transient()
def AddStation(self):
AddStationDialogBox = Toplevel(root) #Tkinter.Tk()
AddStationDialogBox.title('Add Station')
frame = Frame(AddStationDialogBox) #frame for target entry
frame.pack(padx=10, pady=10,side=TOP,fill=X)
bottomframe = Frame(AddStationDialogBox) #froame for host entry
bottomframe.pack(padx=10, pady=10,side=TOP,fill=X)
bottomframe2 = Frame(AddStationDialogBox) #frame for button
bottomframe2.pack(side=TOP)
AddStationDialogBox.transient()
lTargentName = Label(frame, text="Target Name :")
lTargentName.pack(side=LEFT)
TargetName = StringVar()
eTargetEntryField = Entry(frame,width=20)
eTargetEntryField.pack(side=RIGHT,fill=X)
eTargetEntryField.focus()
lHostName = Label(bottomframe, text="Host Name :")
lHostName.pack(side=LEFT)
HostName = StringVar()
eHostNameEntry = Entry(bottomframe,width=20)
eHostNameEntry.pack(side=RIGHT,fill=X)
okbutton = Tkinter.Button(bottomframe2,
text="OK",command=(lambda : self.OkButtonPressed(eTargetEntryField,
AddStationDialogBox)))
okbutton.pack(side=LEFT, padx=10, pady=15)
cancelbutton = Tkinter.Button(bottomframe2, text="CANCEL",
command=(lambda : self.CancelButtonPressed(AddStationDialogBox)))
cancelbutton.pack(side=LEFT, padx=10, pady=15)
AddStationDialogBox.focus()
AddStationDialogBox.bind('<Return>',(lambda event :
self.enter(eTargetEntryField,AddStationDialogBox)))
AddStationDialogBox.mainloop()
if __name__ == "__main__":
root = Tk()
app = SimpleApp(root)
app.mainloop()
--
View this message in context: http://python.6.x6.nabble.com/how-to-get-values-form-the-custom-widget-module-to-the-parent-frame-widget-in-Tkinter-tp5050211.html
Sent from the Python - tkinter-discuss mailing list archive at Nabble.com.
the code is as follows :
from Tkinter import *
from logging import exception
import tkFileDialog
import pickle
import os.path
STATION_NAME, TARGET_NAME, HOST_NAME, TARGET_IP, HOST_IP, EXCEL_FILE =
range(6)
class NAddStation(Frame):
def __init__(self, parent=None):
Frame.__init__(self, parent)
self.pack(side=TOP, expand=YES, fill=BOTH)
self.tempVar = []
# Label Area
self.labels = ["Station Name :", "Target Name :", "Host Name
:", "Target's IP :", "Host's IP :",
"Excel File :"]
self.REMOVE =1
self.ADD = 2
self.UPDATE = 3
# Entry Area
self.Entry_Target_Name = None
self.Entry_Host_Name = None
self.Entry_Target_IP = None
self.Entry_Host_IP = None
self.Entry_Station_Name = None
self.Entry_File_Path = None
#Misc
self.File_Browse_Button = None
self.Add_Button = None
self.Cancel_Button = None
self.createWindow()
def openFileBrowser(self):
filepath = tkFileDialog.askopenfilename()
self.Entry_File_Path.insert(0, filepath)
def validate(self):
print("Adding Data....")
self.Store_Station()
def Remove_Station(self,key):
if os.path.isfile('Station-pickle'):
dbfile = open('Station-pickle', 'rb')
db = pickle.load(dbfile)
dbfile.close()
db.__delitem__(key)
dbfile = open('Station-pickle', 'wb')
pickle.dump(db, dbfile)
dbfile.close()
def returnStationName(self):
return self.tempVar[0].get()
def Store_Station(self):
fl={}
rc={}
fl['SN']= self.tempVar[0].get()
fl['HN']= self.tempVar[1].get()
fl['HP']= self.tempVar[2].get()
fl['TN']= self.tempVar[3].get()
fl['TP']= self.tempVar[4].get()
fl['XL']= self.tempVar[5].get()
station_name = self.tempVar[0].get()
rc[station_name]= fl
if not os.path.isfile('Station-pickle'):
print ("Creating File")
dbfile = open('Station-pickle', 'wb') # use
binary mode files in 3.X
pickle.dump(rc, dbfile) # data is
bytes, not str
else:
print ("Appending File")
# --------
dbfile = open('Station-pickle', 'rb')
db = pickle.load(dbfile)
dbfile.close()
db[station_name] = fl
dbfile = open('Station-pickle', 'wb')
pickle.dump(db, dbfile)
dbfile.close()
dbfile.close()
def Load_Station(self, key_value):
dbfile = open('Station-pickle', 'rb') # use binary
mode files in 3.X
db = pickle.load(dbfile)
for key in db:
if key == key_value:
print("STATION_NAME :" + db[key]['SN'])
print("HOST_NAME :" + db[key]['HN'])
print("HOST_IP :" + db[key]['HP'])
print("TARGET_NAME :" + db[key]['TN'])
print("TARGENT_IP :" + db[key]['TP'])
print("FILE_NAME :" + db[key]['XL'])
return ("STATION_NAME :" + db[key]['SN'] +"\n" +
"HOST_NAME :" + db[key]['HN'] + "\n" + "HOST_IP :" +
db[key]['HP'] + "\n" + "TARGET_NAME :" + db[key]['TN'] + "\n" +
"TARGENT_IP :" + db[key]['TP'] + "\n" + "FILE_NAME :" +
db[key]['XL'])
print "No Station with Name " + key_value
dbfile.close()
def createWindow(self):
# Station Entry
Label(self, text=self.labels[STATION_NAME]).grid(row=0,
column=0)
self.Entry_Station_Name = Entry(self, width=20)
self.tempVar.append(self.Entry_Station_Name)
self.Entry_Station_Name.grid(row=0, column=1)
# Host Entry
Label(self, text=self.labels[HOST_NAME]).grid(row=1, column=0)
self.Entry_Host_Name = Entry(self, width=20)
self.tempVar.append(self.Entry_Host_Name)
self.Entry_Host_Name.grid(row=1, column=1)
Label(self, text=self.labels[HOST_IP]).grid(row=1, column=2)
self.Entry_Host_IP = Entry(self, width=20)
self.tempVar.append(self.Entry_Host_IP)
self.Entry_Host_IP.grid(row=1, column=3)
# Target Entry
Label(self, text=self.labels[TARGET_NAME]).grid(row=2, column=0)
self.Entry_Target_Name = Entry(self, width=20)
self.tempVar.append(self.Entry_Target_Name)
self.Entry_Target_Name.grid(row=2, column=1)
Label(self, text=self.labels[TARGET_IP]).grid(row=2, column=2)
self.Entry_Target_IP = Entry(self, width=20)
self.tempVar.append(self.Entry_Target_IP)
self.Entry_Target_IP.grid(row=2, column=3)
#Browser Button
Label(self, text=self.labels[EXCEL_FILE]).grid(row=3, column=0)
self.Entry_File_Path = Entry(self, width=50)
self.tempVar.append(self.Entry_File_Path)
self.Entry_File_Path.grid(row=3, column=1)
self.File_Browse_Button = Button(self, text="Browse",
command=self.openFileBrowser, width=10,justify=CENTER).grid(row=3, column=3)
Button(self, text="Add", command=(lambda : self.validate()),
width=10,justify=CENTER).grid(row=4, column=1)
Button(self, text="Cancel", command=
self.winfo_toplevel().destroy, width=10,justify=CENTER).grid(row=4,
column=2)
self.Entry_Station_Name.focus()
**Now I want to use the above mentioned Custom Frame in Main app , when i
ckick on AddStation from menu file the custome Frame pops up , I can add
the data but when i click on ok , i want the data to apear on the textArea ,
represented by Self.Entity2 in the following code:**
from Tkconstants import LEFT, BOTTOM, X, TOP, RIGHT, ACTIVE, Y
from Tkinter import Tk, Frame, Menu, END, Label, YES, BOTH, Entry,
StringVar, Toplevel
import Tkinter
import sys
from make_db_pickle import *
class SimpleApp(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.pack(expand=YES, fill=BOTH)
self.master.title('GUI')
self.initialize(parent)
self.TargetName = None
self.HostName = None
self.eHostNameEntry =None
self.sbar = None
self.AddWidget = None
def CancelButtonPressed(self, widget):
# print "Cancel Button Pressed"
widget.destroy()
def AddEntryToListBox(self,entry):
self.entry1.insert(END, entry)
def enter(event,entry,widget):
event.OkButtonPressed(entry,widget)
def OkButtonPressed(self,entry,widget):
print "Ok bution pressed"
self.AddEntryToListBox(str(entry.get()).upper())
widget.destroy()
def runCommand(self, selection): # redefine me
lower
self.entry2.insert('1.0',"The following Station was selected " +
selection)
self.entry3.insert('1.0',"The following Station was selected " +
selection)
self.entry4.insert('1.0',"The following Station was selected " +
selection)
print('You selected:', selection)
def handleList(self, event):
index = self.entry1.curselection() # on list
double-click
label = self.entry1.get(index) # fetch
selection text
self.runCommand(label) # and call
action here
def initialize(self, parent):
menubar = Menu(self.parent)
self.parent.config(menu=menubar)
self.sbar = Tkinter.Scrollbar(self)
fileMenu = Menu(menubar, tearoff = False)
fileMenu.add_command(label="Add Station",
command=self.AddNewStation)
fileMenu.add_command(label="Delete Station",
command=self.onExit)
fileMenu.add_separator()
fileMenu.add_command(label="Exit", command=self.onExit)
menubar.add_cascade(label="File", menu=fileMenu)
self.grid()
self.entry1 = Tkinter.Listbox(self, height=24, yscrollcommand=1,
bg="white")
# --------------------------
self.sbar = Tkinter.Scrollbar(self)
self.sbar.config(command=self.entry1.yview) #
xlink sbar and list
self.entry1.config(yscrollcommand=self.sbar.set) #
move one moves other
self.entry1.pack(side=LEFT, expand=YES, fill=BOTH) # list
clipped first
# pos = 0
#list.config(selectmode=SINGLE, setgrid=1) #
select,resize modes
self.entry1.bind('<Double-1>', self.handleList) # set
event handler
# --------------------------
# for i in acts:
# self.entry1.insert(END, i)
# self.entry1 = Tkinter.Text(self)
self.entry1.grid(column=0, row=0, sticky='EW')
self.entry2 = Tkinter.Text(self)
self.entry2.grid(column=1, row=0, sticky='EW', padx=1, pady=1)
self.entry3 = Tkinter.Text(self)
self.entry3.grid(column=0, row=1, sticky='EW', padx=1, pady=1)
self.entry4 = Tkinter.Text(self)
self.entry4.grid(column=1, row=1, sticky='EW', padx=1, pady=1)
def onExit(self):
sys.exit()
def AddNewStation(self):
n = Toplevel(root)
n.title("Add Station")
self.AddWidget = NAddStation(n)
n.transient()
def AddStation(self):
AddStationDialogBox = Toplevel(root) #Tkinter.Tk()
AddStationDialogBox.title('Add Station')
frame = Frame(AddStationDialogBox) #frame for target entry
frame.pack(padx=10, pady=10,side=TOP,fill=X)
bottomframe = Frame(AddStationDialogBox) #froame for host entry
bottomframe.pack(padx=10, pady=10,side=TOP,fill=X)
bottomframe2 = Frame(AddStationDialogBox) #frame for button
bottomframe2.pack(side=TOP)
AddStationDialogBox.transient()
lTargentName = Label(frame, text="Target Name :")
lTargentName.pack(side=LEFT)
TargetName = StringVar()
eTargetEntryField = Entry(frame,width=20)
eTargetEntryField.pack(side=RIGHT,fill=X)
eTargetEntryField.focus()
lHostName = Label(bottomframe, text="Host Name :")
lHostName.pack(side=LEFT)
HostName = StringVar()
eHostNameEntry = Entry(bottomframe,width=20)
eHostNameEntry.pack(side=RIGHT,fill=X)
okbutton = Tkinter.Button(bottomframe2,
text="OK",command=(lambda : self.OkButtonPressed(eTargetEntryField,
AddStationDialogBox)))
okbutton.pack(side=LEFT, padx=10, pady=15)
cancelbutton = Tkinter.Button(bottomframe2, text="CANCEL",
command=(lambda : self.CancelButtonPressed(AddStationDialogBox)))
cancelbutton.pack(side=LEFT, padx=10, pady=15)
AddStationDialogBox.focus()
AddStationDialogBox.bind('<Return>',(lambda event :
self.enter(eTargetEntryField,AddStationDialogBox)))
AddStationDialogBox.mainloop()
if __name__ == "__main__":
root = Tk()
app = SimpleApp(root)
app.mainloop()
--
View this message in context: http://python.6.x6.nabble.com/how-to-get-values-form-the-custom-widget-module-to-the-parent-frame-widget-in-Tkinter-tp5050211.html
Sent from the Python - tkinter-discuss mailing list archive at Nabble.com.