Return value from text entry to some other class - python-3.x

I am trying to get return values from tkinter window where i am entering text values,I want those text values to be returned so that I can capture those and send as input to other class methods.
I am able to print those captured values but not able to return them. I am very new to python
from tkinter import *
class gui_cls:
def __init__(self,*args):
self.master=args[0]
self.delete = StringVar()
self.insert = StringVar()
self.var1 = IntVar()
self.var3 = IntVar()
def vergui(self):
Delete = self.delete.get()
insertversions = self.insert.get()
prog = self.var1.get()
print(Delete)
print(insertversions)
if prog:
print("levels")
else:
pass
label_0 = Label(self.master, text="Adaptive", width=20, font=("bold", 20))
label_0.place(x=40, y=53)
label_1 = Label(self.master, text="Delete Versions", width=20, font=("bold", 10))
label_1.place(x=30, y=130)
entry_1 = Entry(root, textvar=self.delete)
entry_1.place(x=200, y=130)
label_2 = Label(self.master, text="Insert Versions", width=20, font=("bold", 10))
label_2.place(x=30, y=180)
entry_2 = Entry(self.master, textvar=self.insert)
entry_2.place(x=200, y=180)
label_3 = Label(self.master, text="Reload", width=20, font=("bold", 10))
label_3.place(x=30, y=230)
var2 = IntVar()
Checkbutton(self.master, text="Levels", padx=5, variable=self.var1).place(x=190, y=230)
Checkbutton(self.master, text="Accounts", padx=20, variable=var2).place(x=250, y=230)
label_4 = Label(self.master, text="Note: Please seperate versions by comma(,)", fg='red', font=("bold", 13)).place(x=30, y=280)
Button(self.master, text='Finish', width=20, bg='brown', fg='white', command=self.vergui).place(x=200, y=350)
root = Tk()
root.geometry('400x400')
root.title("Adaptive")
gui_cls(root).vergui()
root.mainloop()

Current you created an instance of the class on the fly. You can first define a variable for the instance of the class, and then call the methods separately:
#gui_cls(root).vergui()
gui = gui_cls(root)
gui.vergui()
Then you can access the class attributes anytime.
print (gui.delete.get())
print (gui.var1.get())
...

Related

how to delete a specific item in the list after a button is clicked in tkinter python

Below is a small code where if you click add button a pop-up will appear where you write desired number. The number in the bottom represents the sum of all numbers you entered.
What I am trying to achieve is to update the sum_lbl and index_no as I delete any of the labels.
Code:
from tkinter import *
root = Tk()
root.geometry('400x400')
add_room_area_var= StringVar(None)
area_lst = []
index_no = 0
def destroy(widget):
widget.destroy()
def add_():
add_room_area = Toplevel(root)
add_room_area.title('Add Room area')
add_room_area.wm_minsize(200, 50)
add_room_area.resizable(False, False)
add_room_area.transient(root)
add_r_area_frame = LabelFrame(add_room_area, text=' Room area ', labelanchor=N)
add_r_area_frame.config(padx=3, pady=3)
add_r_area_frame.pack(fill=X, padx=10, pady=10)
add_r_area_entry = Entry(add_r_area_frame, textvariable=add_room_area_var)
add_r_area_entry.pack(fill=X)
add_r_area_entry.focus_set()
while True:
def ok_():
global index_no
name = add_room_area_var.get()
index_no += 1
entry_frame = Frame(root)
index_lbl = Label(entry_frame, text=index_no)
add_room_lbl = Label(entry_frame, text=name, width=12, bg='gray30', fg='white', pady=5)
close_button = Button(entry_frame, text='X', command=lambda:destroy(entry_frame))
entry_frame.pack(anchor=N, padx=1)
index_lbl.pack(side=LEFT, padx=3)
add_room_lbl.pack(fill=X, side=LEFT)
close_button.pack(side=RIGHT)
area_lst.append(int(name))
add_room_area.destroy()
area_sum = sum(area_lst)
sum_lbl.config(text=area_sum)
break
ok_button = Button(add_room_area, text='Ok', command=ok_)
ok_button.pack()
btn = Button(root, text='Add', command=add_)
btn.pack()
sum_lbl = Label(root, font=25)
sum_lbl.pack(side=BOTTOM, pady=15)
root.mainloop()
Output:
After deleting the 3rd and 4th label the output is:
I would suggest to change area_lst to dictionary using the frame as the key and the two labels as the value for each row.
Then update destroy() to use area_lst to update the total and indexes:
from tkinter import *
root = Tk()
root.geometry('400x400')
add_room_area_var= StringVar(None)
area_lst = {} # dictionary to hold labels of each row using frame as the key
def destroy(frame):
frame.destroy()
del area_lst[frame]
update_total()
# update index of remaining rows
for idx, (lbl, _) in enumerate(area_lst.values(), 1):
lbl['text'] = idx
# function to update the total label
def update_total():
area_sum = sum(int(room['text']) for _, room in area_lst.values())
sum_lbl.config(text=area_sum)
def add_():
add_room_area = Toplevel(root)
add_room_area.title('Add Room area')
add_room_area.wm_minsize(200, 50)
add_room_area.resizable(False, False)
add_room_area.transient(root)
add_r_area_frame = LabelFrame(add_room_area, text=' Room area ', labelanchor=N)
add_r_area_frame.config(padx=3, pady=3)
add_r_area_frame.pack(fill=X, padx=10, pady=10)
add_r_area_entry = Entry(add_r_area_frame, textvariable=add_room_area_var)
add_r_area_entry.pack(fill=X)
add_r_area_entry.focus_set()
def ok_():
name = add_room_area_var.get()
entry_frame = Frame(root)
index_lbl = Label(entry_frame, text=len(area_lst)+1)
add_room_lbl = Label(entry_frame, text=name, width=12, bg='gray30', fg='white', pady=5)
close_button = Button(entry_frame, text='X', command=lambda:destroy(entry_frame))
entry_frame.pack(anchor=N, padx=1)
index_lbl.pack(side=LEFT, padx=3)
add_room_lbl.pack(fill=X, side=LEFT)
close_button.pack(side=RIGHT)
# store current row to area_lst
area_lst[entry_frame] = (index_lbl, add_room_lbl)
add_room_area.destroy()
update_total()
ok_button = Button(add_room_area, text='Ok', command=ok_)
ok_button.pack()
btn = Button(root, text='Add', command=add_)
btn.pack()
sum_lbl = Label(root, font=25)
sum_lbl.pack(side=BOTTOM, pady=15)
root.mainloop()
You can allow buttons to call multiple commands, so for your 'close_button' button, I added two more commands: remove the name from 'area_lst' and update the 'sum_lbl' text with the new sum for 'area_lst'
Like this:
from tkinter import *
root = Tk()
root.geometry('400x400')
add_room_area_var= StringVar(None)
area_lst = []
index_no = 0
def destroy(widget):
widget.destroy()
def add_():
add_room_area = Toplevel(root)
add_room_area.title('Add Room area')
add_room_area.wm_minsize(200, 50)
add_room_area.resizable(False, False)
add_room_area.transient(root)
add_r_area_frame = LabelFrame(add_room_area, text=' Room area ', labelanchor=N)
add_r_area_frame.config(padx=3, pady=3)
add_r_area_frame.pack(fill=X, padx=10, pady=10)
add_r_area_entry = Entry(add_r_area_frame, textvariable=add_room_area_var)
add_r_area_entry.pack(fill=X)
add_r_area_entry.focus_set()
while True:
def ok_():
global index_no
name = add_room_area_var.get()
index_no += 1
entry_frame = Frame(root)
index_lbl = Label(entry_frame, text=index_no)
add_room_lbl = Label(entry_frame, text=name, width=12, bg='gray30', fg='white', pady=5)
close_button = Button(entry_frame, text='X', command=lambda:[destroy(entry_frame), area_lst.remove(int(name)), sum_lbl.config(text=sum(area_lst))])
entry_frame.pack(anchor=N, padx=1)
index_lbl.pack(side=LEFT, padx=3)
add_room_lbl.pack(fill=X, side=LEFT)
close_button.pack(side=RIGHT)
area_lst.append(int(name))
add_room_area.destroy()
area_sum = sum(area_lst)
sum_lbl.config(text=area_sum)
break
ok_button = Button(add_room_area, text='Ok', command=ok_)
ok_button.pack()
btn = Button(root, text='Add', command=add_)
btn.pack()
sum_lbl = Label(root, font=25)
sum_lbl.pack(side=BOTTOM, pady=15)
root.mainloop()

Is it possible to grab input from the topview tkinter window and retrieve saved entry field value from within master tk window

The program is made up of classes and I am trying to use a tkinter topview from within a function so that when it's called it is able to retrieve the entryfield value to the master class
from tkinter import
from PIL import Image, ImageTk
Below is the driver code handling the transitioning from one class to another
class SeaofBTCapp(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
container = Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (
WelcomePage, Register_new_user): # ,PageThree,PageFour):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(WelcomePage)
# def show_frame(self, cont):
# frame = self.frames[cont]
# frame.tkraise()
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
frame.update()
frame.event_generate("<<show_frame>>")
def get_page(self, cont):
for page in self.frames.values():
if str(page.__class__.__name__) == cont:
return page
return None
class Register_new_user(object):
pass
Below is the entry point of the program and is the first page to be displayed
class WelcomePage(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
# self.bind("<<show_frame>>", self.main_prog)
def resize_image(event):
global photo
new_width = event.width
new_height = event.height
image = copy_of_image.resize((new_width, new_height))
photo = ImageTk.PhotoImage(image)
label.config(image=photo)
label.image = photo # avoid garbage collection
def pin_input():
top = Toplevel()
top.geometry("180x100")
top.title("toplevel")
l2 = Label(top, text="This is toplevel window")
global entry_1
global password
password = StringVar
entry_1 = None
def cleartxtfield():
global password
new = "3"
password.set(new)
# ############# Function to parse for only numerical input
def validate(input):
if input.isdigit():
return True
elif input == "":
return True
else:
return False
def enternumber(x):
global entry_1
setval = StringVar()
setval = str(x)
# print(setval)
entry_1.insert(END, setval)
entry_1 = Entry(top, textvariable=password, width=64, show='*')
entry_1.place(x=200, y=100)
entry_1.focus()
reg = top.register(validate)
entry_1.config(validate="key", validatecommand=(reg, '%P'))
def getcreds():
# check if four digit entered and is not empty
global passwd
passwd = password.get()
print(f"The Credentials are {passwd}")
def funcbackspace():
length = len(entry_1.get())
entry_1.delete(length - 1, 'end')
def killwindow():
# when the user quits it should clear all the data input fields filled in in the previous steps. and should display information that it is about to quit in a few seconds
command = top.destroy()
# Label(top,text="Goodbye\n (Closing in 2 seconds)")
top.after(2000, top.quit())
cancel = Button(top, width=8, height=3, text="Cancel", bg="red", fg="black", command=killwindow)
cancel.place(x=220, y=150)
backspace = Button(top, width=8, height=3, text="Backspace", bg="red", fg="black", command=funcbackspace)
backspace.place(x=500, y=150)
# ----number Buttons------
def enternumber(x):
global entry_1
setval = StringVar()
setval = str(x)
# print(setval)
entry_1.insert(END, setval)
btn_numbers = []
for i in range(10):
btn_numbers.append(
Button(top, width=8, height=3, text=str(i), bd=6, command=lambda x=i: enternumber(x)))
btn_text = 1
for i in range(0, 3):
for j in range(0, 3):
btn_numbers[btn_text].place(x=220 + j * 140, y=250 + i * 100)
btn_text += 1
btn_zero = Button(top, width=15, height=2, text='0', bd=5, command=lambda x=0: enternumber(x))
btn_zero.place(x=330, y=550)
clear = Button(top, text="Clear", bg="green", fg="white", width=8, height=3, command=cleartxtfield)
clear.place(x=220, y=550)
okbtn = Button(top, text="Enter", bg="green", fg="black", width=8, height=3, command=getcreds)
okbtn.place(x=500, y=550)
val = getcreds()
print("The value to be returned is %s" % val)
return val
password = pin_input()
print("Gotten password is %s" % password)
copy_of_image = Image.open("image.png")
photoimage = ImageTk.PhotoImage(copy_of_image)
label = Label(self, image=photoimage)
label.place(x=0, y=0, relwidth=1, relheight=1)
label.bind('<Configure>', resize_image)
top_left_frame = Frame(self, relief='groove', borderwidth=2)
top_left_frame.place(relx=1, rely=0.1, anchor=NE)
center_frame = Frame(self, relief='raised', borderwidth=2)
center_frame.place(relx=0.5, rely=0.75, anchor=CENTER)
Button(top_left_frame, text='REGISTER', bg='grey', width=14, height=1,
command=lambda: controller.show_frame(Register_new_user)).pack()
Button(center_frame, text='ENTER', fg='white', bg='green', width=13, height=2,
command=lambda: controller.show_frame(Register_new_user)).pack()
if __name__ == '__main__':
app = SeaofBTCapp()
app.title("Password return on topview window")
width = 1000
height = 700
screenwidth = app.winfo_screenwidth()
screenheight = app.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
app.geometry(alignstr)
# app.resizable(width=False, height=False)
app.resizable(width=True, height=True)
app.mainloop()
If I understand this correctly you want to enter a password in a dialog and then get the password from the dialog when you close it.
Have a look at Dialog Windows at effbot for a discussion about creating dialog windows.
Here is an example of how you can implement a simple dialog:
from tkinter import *
from tkinter import simpledialog
class MyDialog(simpledialog.Dialog):
def body(self, master):
'''create dialog body.
return widget that should have initial focus.
This method should be overridden, and is called
by the __init__ method.'''
Label(master, text='Value:').grid(row=0)
self.e1 = Entry(master)
self.e1.grid(row=0, column=1)
return self.e1 # initial focus
def apply(self):
'''process the data
This method is called automatically to process the data, *after*
the dialog is destroyed. By default, it does nothing.'''
value = self.e1.get()
self.result = value
def validate(self):
'''validate the data
This method is called automatically to validate the data before the
dialog is destroyed. By default, it always validates OK.'''
return 1 # override
def buttonbox(self):
'''add standard button box.
override if you do not want the standard buttons
'''
box = Frame(self)
w = Button(box, text="OK", width=10, command=self.ok, default='active')
w.pack(side='left', padx=5, pady=5)
w = Button(box, text="Cancel", width=10, command=self.cancel)
w.pack(side='left', padx=5, pady=5)
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.cancel)
box.pack()
if __name__ == '__main__':
root = Tk()
root.geometry('200x100+800+50')
def do():
d = MyDialog(root)
print(d.result)
b = Button(root, text='Go!', width=10, command=do)
b.pack(expand=True)
Did that answer your question?

SQLite Python Query not working when using tkinter with no error messages

I am learning python for my A level and have come across a problem in my project, any help would be immensely appreciated. Thank you.
I have a series of tkinter pages that are designed to be linked by one central page. The search, delete and update functions successfully run SQL queries on their own but lose their functionality when called from the main page, I am getting no visible error messages. I am running SQLite 3.11.2 and Python 3.7.3
The main page calls the attendance page like this (triggered using a button):
def ap():
AttendancePage.Attendance(Tk())
The actual attendance page is as follows:
import tkinter as tk
from tkinter import*
import tkinter.messagebox
import NEA_SQL_IIII
class Attendance:
def __init__ (self,root):
self.root =root
self.root.title("ODIN Attendance Page")
self.root.geometry("1350x750+0+0")
self.root.config(bg="ghost white")
#These are all the entry widgets, where the values will be added
Absent = BooleanVar()
AbsenceNote = BooleanVar()
TotalAbsences = IntVar()
StudentName = StringVar()
StudentID = StringVar()
should_auto = BooleanVar()
#function
#This is the section that will give the buttons their functionality
def Clear():
self.entStudentID.delete(0,END)
self.entStudentName.delete(0,END)
self.chkAbsent.deselect()
self.chkAbsenceNote.deselect()
self.entTotalAbsences.delete(0,END)
def Exit():
Exit = tk.messagebox.askyesno("ODIN","Do you wish to exit?")
if Exit > 0:
root.destroy()
return
def searchDatabase():
attendanceList.delete(0,END)
for row in NEA_SQL_IIII.searchA(StudentID.get(),StudentName.get()):
attendanceList.insert(END,row,str(""))
def viewData():
attendanceList.delete(0,END)
for row in NEA_SQL_IIII.displayA():
attendanceList.insert(END,row,str(""))
def deleteData():
if(len(StudentName.get())!=0):
NEA_SQL_IIII.DeleteDataA(sd[0])
Clear()
viewData()
def AttendRec(event):
global sd
searchAttend = attendanceList.curselection()[0]
sd = attendanceList.get(searchAttend)
self.entStudentID.delete(0,END)
self.entStudentID.insert(END,sd[0])
self.entStudentName.delete(0,END)
self.entStudentName.insert(END,sd[1])
self.chkAbsent.deselect()
self.chkAbsent.select()
self.chkAbsenceNote.deselect()
self.chkAbsenceNote.select()
self.entTotalAbsences.delete(0,END)
self.entTotalAbsences.insert(END,sd[4])
def Update():
if(len(StudentID.get())!=0):
NEA_SQL_IIII.DeleteDataA(sd[0])
if(len(StudentID.get())!=0):
NEA_SQL_IIII.addStudentA(StudentID.get(),StudentName.get(),Absent.get(),AbsenceNote.get(),TotalAbsences.get())
attendanceList.delete(0,END)
attendanceList.insert(END,(StudentID.get(),StudentName.get(),Absent.get(),AbsenceNote.get(),TotalAbsences.get()))
#Frames
#These will define all the different frames
MainFrame = Frame(self.root, bg="Ghost White")
MainFrame.grid()
TitFrame = Frame(MainFrame, bd=2, padx=54, pady=8, bg="Ghost White", relief = RIDGE)
TitFrame.pack(side=TOP)
self.lblTit = Label(TitFrame ,font=('ariel', 47,'bold'),text="ODIN Attendance Page",bg="Ghost White")
self.lblTit.grid()
ButtonFrame = Frame(MainFrame, bd=2, width=1350, height=70, padx=18, pady=10, bg="blue2", relief = RIDGE)
ButtonFrame.pack(side=BOTTOM)
DataFrame = Frame(MainFrame, bd=1, width=1300, height=400, padx=20, pady=20, bg="ghost white", relief = RIDGE)
DataFrame.pack(side=BOTTOM)
#DataFrameTOP = LabelFrame(DataFrame, bd=1, width=1000, height=300, padx=20, pady=4, relief = RIDGE, bg="Ghost White", font=('ariel', 20,'bold'), text = "Student Info\n")
#DataFrameTOP.pack(side=TOP)
DataFrameLEFT = LabelFrame(DataFrame, bd=1, width=450, height=200, padx=20,pady=3, bg="Ghost White", relief = RIDGE, font=('ariel', 20,'bold'), text = "Student Info\n")
DataFrameLEFT.pack(side=LEFT)
DataFrameRIGHT = LabelFrame(DataFrame, bd=1, width=450, height=200, padx=31,pady=3, bg="Ghost White", relief = RIDGE, font=('ariel', 20,'bold'), text = "Student Details\n")
DataFrameRIGHT.pack(side=RIGHT)
#Label and Entry Widget
#These are the widgets that will allow for labels onto the entry sections
self.lblStudentID = Label(DataFrameLEFT ,font=('ariel', 11,'bold'),text="Student ID", padx=2, pady=2, bg="Ghost White")
self.lblStudentID.grid(row=0, column=0, sticky=W)
self.entStudentID = Entry(DataFrameLEFT ,font=('ariel', 11,'bold'),textvariable=StudentID, width=39)
self.entStudentID.grid(row=0, column=1)
self.lblStudentName = Label(DataFrameLEFT ,font=('ariel', 11,'bold'),text="Student Name", padx=2, pady=2, bg="Ghost White")
self.lblStudentName.grid(row=1, column=0, sticky=W)
self.entStudentName = Entry(DataFrameLEFT ,font=('ariel', 11,'bold'),textvariable=StudentName, width=39)
self.entStudentName.grid(row=1, column=1)
self.lblAbsent = Label(DataFrameLEFT ,font=('ariel', 11,'bold'),text="Absent?", padx=2, pady=2, bg="Ghost White")
self.lblAbsent.grid(row=2, column=0, sticky=W)
self.chkAbsent = Checkbutton(DataFrameLEFT ,font=('ariel', 11,'bold'),textvariable=Absent, variable = should_auto, onvalue = True, offvalue = False, width=39)
self.chkAbsent.grid(row=2, column=1)
self.lblAbsenceNote = Label(DataFrameLEFT ,font=('ariel', 11,'bold'),text="Absence Note?", padx=2, pady=2, bg="Ghost White")
self.lblAbsenceNote.grid(row=3, column=0, sticky=W)
self.chkAbsenceNote = Checkbutton(DataFrameLEFT ,font=('ariel', 11,'bold'),textvariable=AbsenceNote, width=39, onvalue = True, offvalue = False)
self.chkAbsenceNote.grid(row=3, column=1)
self.lblTotalAbsences = Label(DataFrameLEFT ,font=('ariel', 11,'bold'),text="Total Absences?", padx=2, pady=2, bg="Ghost White")
self.lblTotalAbsences.grid(row=4, column=0, sticky=W)
self.entTotalAbsences = Entry(DataFrameLEFT ,font=('ariel', 11,'bold'),textvariable=TotalAbsences, width=39)
self.entTotalAbsences.grid(row=4, column=1)
#scrollbar
scrollbar = Scrollbar(DataFrameRIGHT)
scrollbar.grid(row=0, column=1, sticky = 'ns')
attendanceList = Listbox(DataFrameRIGHT, width=41, height=16, font=('ariel',12,'bold'), yscrollcommand=scrollbar.set)
attendanceList.bind('<<ListboxSelect>>',AttendRec)
attendanceList.grid(row=0, column=0, padx=8)
scrollbar.config(command = attendanceList.yview)
#button
#self.btnAddDate = Button(ButtonFrame, text='Add New', font=('ariel',20,'bold'),height=1,width=10, bd=4, command=addData)
#self.btnAddDate.grid(row=0, column=0)
self.btnDisplay = Button(ButtonFrame, text='Display', font=('ariel',20,'bold'),height=1,width=10, bd=4, command=viewData)
self.btnDisplay.grid(row=0, column=0)
self.btnClear = Button(ButtonFrame, text='Clear', font=('ariel',20,'bold'),height=1,width=10, bd=4, command=Clear)
self.btnClear.grid(row=0, column=1)
self.btnDelete = Button(ButtonFrame, text='Delete', font=('ariel',20,'bold'),height=1,width=10, bd=4, command = deleteData)
self.btnDelete.grid(row=0, column=2)
self.btnSearch = Button(ButtonFrame, text='Search', font=('ariel',20,'bold'),height=1,width=10, bd=4, command = searchDatabase)
self.btnSearch.grid(row=0, column=3)
#self.btnUpdate = Button(ButtonFrame, text='Update', font=('ariel',20,'bold'),height=1,width=10, bd=4, command = updateData)
#self.btnUpdate.grid(row=0, column=4)
self.btnUpdate = Button(ButtonFrame, text='Update', font=('ariel',20,'bold'),height=1,width=10, bd=4, command = Update)
self.btnUpdate.grid(row=0, column=4)
self.btnQuit = Button(ButtonFrame, text='Quit', font=('ariel',20,'bold'),height=1,width=10, bd=4, command=Exit)
self.btnQuit.grid(row=0, column=5)
if __name__=='__main__':
root = tk.Tk()
application = Attendance(root)
root.mainloop()'''
The SQL code that is being called is:
def Attendance():
con=sqlite3.connect("Attendance.db")
cur=con.cursor()
cur.execute("CREATE TABLE IF NOT EXIST Attendance (Absent BOOLEAN, AbsenceNote BOOLEAN, TotalAbsences INTEGER, FOREIGN KEY StudentName REFERENCES StudentRecord(StudentName),FOREIGN KEY StudentID REFERENCES StudentRecord(StudentID), PRIMARY KEY(StudentID)")
con.commit()
con.close()
def displayA():
con=sqlite3.connect("Attendance.db")
cur=con.cursor()
cur.execute("SELECT * FROM Attendance")
rows =cur.fetchall()
con.close()
return rows
def DeleteDataA(StudentID):
con=sqlite3.connect("Attendance.db")
cur=con.cursor()
cur.execute("DELETE FROM Attendance WHERE StudentID=?", (StudentID,))
con.commit()
return con, cur
con.close()
def searchA(StudentName="", StudentID=""):
con=sqlite3.connect("Attendance.db", isolation_level=None)
cur=con.cursor()
cur.execute("SELECT * FROM Attendance WHERE StudentName=? OR StudentID=?", (StudentName,StudentID,))
rows = cur.fetchall()
con.close()
return rows
def UpdateDataA(StudentID="", StudentName="", Behaviour="", Achievement="", Detention="", ProgressLevel=""):
con=sqlite3.connect("StudentRecord.db")
cur=con.cursor()
cur.execute("UPDATE StudentRecord SET StudentName=?, Behaviour=?, Achievement=?, Detention=?, ProgressLevel=? WHERE StudentID=? ", (StudentID,StudentName,Behaviour,Achievement,Detention,ProgressLevel))
con.commit()
con.close()

Change Entry widget value from other function

I am quite new in programming with tkinter , especially with classes. How can I make a button that runs function from the same class and changes entry widget. In my code i want to change entry1 whenever button1 is clicked and filepath function runs.
thank you for your help.
Class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
def filepath():
filename = fd.askopenfilename()
entry1.delete(0,END)
entry1.insert(0,filename)
def initUI(self):
self.master.title("EFEKTYWNOŚĆ APP")
self.pack(fill=BOTH, expand=True)
cd = (os.getcwd())
frame1 = Frame(self)
frame1.pack(side = LEFT)
lbl1 = Label(frame1,
text="...",
wraplength = 250 )
lbl1.pack(side=LEFT, padx=5, pady=5)
path = os.path.join(cd, 'ico', '...')
photo = PhotoImage(file = path)
cphoto = photo.subsample(4,4)
button1 = Button(frame1,
text='WYBIERZ PLIK',
image = cphoto,
compound = LEFT,
command = Example.filepath)
button1.image = cphoto
button1.pack(side=LEFT, fill = Y, padx=5, pady=5)
entry1 = Entry(frame1)
entry1.pack(side=LEFT, fill = Y, padx=5, pady=5)
There are some minor things needed to be fixed in your code. I have added a working sample with comments below.
from tkinter import *
from tkinter import filedialog as fd
import os
class Example(Frame):
def __init__(self, master,**kwargs): #have your Frame accept parameters like how a normal frame should
super().__init__(master,**kwargs)
self.master = master #set master as an attribute so you can access it later
self.initUI()
def filepath(self): #add self to make the method an instance method
filename = fd.askopenfilename()
self.entry1.delete(0, END) #use self when referring to an instance attribute
self.entry1.insert(0, filename)
def initUI(self):
self.master.title("EFEKTYWNOŚĆ APP")
self.pack(fill=BOTH, expand=True)
cd = (os.getcwd())
frame1 = Frame(self)
frame1.pack(side=LEFT)
lbl1 = Label(frame1,
text="...",
wraplength=250)
lbl1.pack(side=LEFT, padx=5, pady=5)
path = os.path.join(cd, 'ico', '...')
photo = PhotoImage(file=path)
cphoto = photo.subsample(4, 4)
button1 = Button(frame1,
text='WYBIERZ PLIK',
image=cphoto,
compound=LEFT,
command=self.filepath) #refer to instance methods by self.your_method
button1.pack(side=LEFT, fill=Y, padx=5, pady=5)
self.entry1 = Entry(frame1) #add self to make it an instance attribute
self.entry1.pack(side=LEFT, fill=Y, padx=5, pady=5) #you will then need to use self.entry1 within your class instance
root = Tk()
Example(root)
root.mainloop()

My program doesn't work when i compile it?

i made a tkinter program. the program is working well when i run it. but when i compile it using cx_Freeze it work well when i use the command python setup.py build . but when i use the command python setup.py bdist_msi to build a simple installer.it doesn't work well and doesn't do his functionality
i am using python 3.6.2 64bit
this is my setup.py:
import cx_Freeze
import sys
import os.path
PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6')
os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6')
base = None
if sys.platform == 'win32':
base = "Win32GUI"
executables = [cx_Freeze.Executable("Tasks_Organiser.py", base=base, icon="iccon.ico")]
cx_Freeze.setup(
name = "Tasks Organiser",
options = {"build_exe": {"packages":["tkinter","sqlite3"], "include_files":["iccon.ico", "favicon.ico", "Notes.db", os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll'),
os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll')]}},
version = "0.01",
description = "GUI APP",
executables = executables
)
and this is my program:
from tkinter import *
from tkinter import ttk
from time import ctime
from tkinter import messagebox
import sqlite3
class Organise:
def __init__(self):
self.conn = sqlite3.connect("Notes.db")
self.conn.row_factory = sqlite3.Row
self.c = self.conn.cursor()
self.c.execute("CREATE TABLE IF NOT EXISTS organise (TaskName TEXT, timefrom TEXT, timeto TEXT, Comment TEXT, TaskType TEXT)")
self.conn.commit()
def add_to_db(self, taskname, From, To, Comment, task_type):
self.c.execute("INSERT INTO organise (TaskName, timefrom, timeto, Comment, TaskType) VALUES (?, ?, ?, ?, ?)", (taskname, From, To, Comment, task_type))
self.conn.commit()
def call_from_db(self):
call = self.c.execute("SELECT * FROM organise").fetchall()
return call
def select_tasks(self):
select = self.c.execute("SELECT TaskName FROM organise")
return select
def delete(self, task):
self.c.execute("DELETE FROM organise WHERE TaskName ='{}'".format(task))
self.conn.commit()
def select_row(self, task):
self.c.execute("SELECT TaskName, timefrom, timeto, Comment, TaskType FROM organise WHERE TaskName = '%s'"%task)
def add():
add = AddTask()
root = Tk()
root.title("OrganiseNotes")
root.iconbitmap("favicon.ico")
root.configure(background="#00b4f0")
style = ttk.Style()
style.configure("TLabel", background="#00b3ad")
style.configure("TButton", background="#173701", forebackground="black", relief="flat")
style.map("TButton",
foreground=[('pressed', '#4b63a1'), ('active', '#00b4f0')],
background=[('pressed', '!disabled', 'black'), ('active', '#2d74ae')])
style.configure("TRadiobutton", background="#e3e2dd")
style.configure("Treeview", background='#adaca7')
# the organise label with the date of that day(today)
today = ctime()[:10]+ctime()[19:]
start_label = ttk.Label(root, text="Organise {}".format(today), font=("Helvetica", 18, "bold"), compound="center")
start_label.grid(row=0, column=0, columnspan=2, padx=10, pady=10)
# the Add task Button
add_bu = ttk.Button(root, text="Add Task")
add_bu.grid(row=1, column=2, padx=10)
add_bu.config(command=add)
# the delete button
dele_bu = ttk.Button(root, text="Delete")
dele_bu.grid(row=2, column=2, padx=10)
# end the day Button (Production of your day)
endday_bu = ttk.Button(root, text="End The Day")
endday_bu.grid(row=3, column=2, padx=10)
class TvShow:
def __init__(self):
self.organ = Organise()
self.tv = ttk.Treeview(root)
self.tv.grid(row=1, column=0, columnspan=2, rowspan=3, padx=10, pady=30)
self.tv.heading("#0", text="ID")
self.tv.configure(column=("#TaskName", "#From", "#To", "#Comment", "#TaskType"))
self.tv.heading("#TaskName", text="TaskName")
self.tv.heading("#From", text="From")
self.tv.heading("#To", text="To")
self.tv.heading("#Comment", text="Comment")
self.tv.heading("#TaskType", text="TaskType")
self.tv.column("#0", width=50)
self.tv.column("#TaskName", width=200, anchor="center")
self.tv.column("#From", width=100, anchor="center")
self.tv.column("#To", width=100, anchor="center")
self.tv.column("#Comment", width=300, anchor="center")
self.i = 1
self.s = self.organ.call_from_db()
def add_to_tv(self, taskname, tfrom, tto, comment, task_type):
self.tv.insert("", "end", text=str(self.i), values=(taskname, tfrom, tto, comment, task_type))
self.i += 1
def del_from_tv(self):
choose = self.tv.selection()
if len(choose) != 0:
choose2 = choose[0]
item_name = self.tv.item(choose2)["values"][0]
self.organ.delete(item_name)
self.tv.delete(choose)
return messagebox.showinfo(title="Task deleted", message="The Task is deleted")
else:
return messagebox.showerror(title="Error", message="Select the task you want to delete")
class AddTask:
def __init__(self):
self._root = Toplevel()
self._root.configure(background="#00b4f0")
self._root.iconbitmap("favicon.ico")
# the task name section
ttk.Label(self._root, text="Task Name").grid(row=0, column=0, padx=10, pady=10)
self.taskname_enter = ttk.Entry(self._root)
self.taskname_enter.grid(row=0, column=1)
# the from (time) section
ttk.Label(self._root, text="From : ").grid(row=1, column=0, padx=10, pady=10)
ttk.Label(self._root, text="hour").grid(row=1, column=1)
self.From_enter_hour = ttk.Entry(self._root, width=5)
self.From_enter_hour.grid(row=1, column=2, padx=20)
ttk.Label(self._root, text=":").grid(row=1, column=3)
ttk.Label(self._root, text="minutes").grid(row=1, column=4)
self.From_enter_min = ttk.Entry(self._root, width=5)
self.From_enter_min.grid(row=1, column=5, padx=5, pady=5)
# the to (time) section
ttk.Label(self._root, text="To:").grid(row=2, column=0)
ttk.Label(self._root, text="hour").grid(row=2, column=1)
self.To_enter_hour = ttk.Entry(self._root, width=5)
self.To_enter_hour.grid(row=2, column=2)
ttk.Label(self._root, text=":").grid(row=2, column=3)
ttk.Label(self._root, text="minutes").grid(row=2, column=4)
self.To_enter_min = ttk.Entry(self._root, width=5)
self.To_enter_min.grid(row=2, column=5,padx=5, pady=5)
# the comment section
ttk.Label(self._root, text="Comment").grid(row=3, column=0, padx=10, pady=10)
self.comment_enter = Text(self._root, width=20, height=10)
self.comment_enter.grid(row=3, column=1)
# the task type section
ttk.Label(self._root, text="Task Type").grid(row=4, column=0, padx=10, pady=10)
self.value_type = StringVar()
self.R1 = ttk.Radiobutton(self._root, text="Very Important", variable=self.value_type, value="Very Important")
self.R1.grid(row=4, column=1, padx=10, pady=10)
self.R2 = ttk.Radiobutton(self._root, text=" Important", variable=self.value_type, value="Important")
self.R2.grid(row=5, column=1, padx=10, pady=10)
self.R3 = ttk.Radiobutton(self._root, text=" Not Important", variable=self.value_type, value="Not Important")
self.R3.grid(row=6, column=1)
# the save button section
self.save_bu = ttk.Button(self._root, text="Save")
self.save_bu.grid(row=7, column=4, padx=10, pady=10)
self.save_bu.config(command=self.busave)
self._root.mainloop()
def busave(self):
try:
check_from_hour = int(self.From_enter_hour.get())
check_from_min = int(self.From_enter_min.get())
check_to_hour = int(self.To_enter_hour.get())
check_to_min = int(self.To_enter_min.get())
From_enter= str(check_from_hour)+":"+str(check_from_min)
To_enter = str(check_to_hour) + ":" + str(check_to_min)
self.organ = Organise()
self.organ.add_to_db(self.taskname_enter.get(), From_enter, To_enter, self.comment_enter.get(1.0, "end"), self.value_type.get())
self.s = self.organ.call_from_db()
row = self.s[-1]
tv.add_to_tv(row[0], row[1], row[2], row[3], row[4])
self.taskname_enter.delete(0, "end")
self.From_enter_hour.delete(0, "end")
self.From_enter_min.delete(0, "end")
self.To_enter_hour.delete(0, "end")
self.To_enter_min.delete(0, "end")
self.comment_enter.delete(1.0, "end")
self.value_type.set("")
except:
messagebox.showinfo(title="invalid inputs", message="From and To inputs should be numbers(ex: 3:56)")
class ProductionDay:
def __init__(self):
self.organ = Organise()
self.tasks = self.organ.select_tasks()
self.tasks_list = []
for i in self.tasks:
self.tasks_list.append(i[0])
self.check = [IntVar(value=0) for i in range(len(self.tasks_list))]
if len(self.tasks_list) != 0:
self.root = Toplevel()
self.root.configure(background="#00b4f0")
self.root.iconbitmap("favicon.ico")
self.root.iconbitmap("favicon.ico")
self.root.title("Your Productivity of Today")
for x in range(len(self.tasks_list)):
ttk.Label(self.root, text=self.tasks_list[x]).grid(row=x, column=0, padx = 10, pady=10)
chech_button = ttk.Checkbutton(self.root, text="done", variable=self.check[x], onvalue=1, offvalue=0).grid(row=x, column=2, padx=10, pady=10)
save_button = ttk.Button(self.root, text="My Productivity")
save_button.grid(row=len(self.tasks_list), column=1, padx=150, pady=10)
save_button.config(command=lambda:self.precentage(self.check))
self.root.mainloop()
else:
messagebox.showerror(title="Error", message="There are no tasks to show")
def precentage(self, checks):
checked_ones = [i.get() for i in checks]
one_count = checked_ones.count(1)
percentage = (one_count/len(checked_ones))*100
messagebox.showinfo(title="Productivity of %s"%today, message="Your Productivity is %s" %str(percentage))
self.root.quit()
def product():
pro = ProductionDay()
endday_bu.config(command= lambda:product())
tv = TvShow()
dele_bu.config(command=lambda:tv.del_from_tv())
for row in tv.s:
tv.add_to_tv(row[0], row[1], row[2], row[3], row[4])
root.mainloop()
Create a folder in your drive C and name it LOCAL_TO_PYTHON, then create another folder inside it and named it PYTHON35-32.Go to the folder or directory where you have your python installed and search the folder named tcl and copy and paste it PYTHON35-32.
Go to your python directory and search for DLL folder inside the folder copy tcl and tk86 and paste it in the tcl folder your copied to the folder you created.
Then convert the program again the issue will be solved . Pay attention to how i named the folders i created.
see this link to resolve it

Resources