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
Related
I want to activate the second entry when the checkbox is checked...but the it works the other way around. What am I doing wrong? Based on another question I have posted it seems the event "<ButtonRelease>" occurs before the bonding. Why is that? Can I use "command" in the checkbox instaed?
import tkinter as tk
def set_entry_status(event, var, widg):
print(var.get())
if var.get():
widg[-1]['state'] = 'normal'
else:
widg[-1]['state'] = 'disabled'
def CustomWidget(frame, name, unit, ):
var_e = []
widget_e = []
var_c = tk.IntVar(master=frame, value=0)
widget_c = tk.Checkbutton(master=frame, text='', variable=var_c)
widget_c.grid(row=0, column=0, columnspan=1, padx=5, pady=5, sticky="ns")
label_l = name + " (" + unit + ")" # nome + unità di misura in parentesi per GUI
widget_l = tk.Label(frame, text=label_l, padx=1, pady=1)
widget_l.grid(row=0, column=1, columnspan=1, padx=5, pady=5, sticky="wns")
var_e.append(tk.StringVar(master=frame, value='A'))
widget_e.append(tk.Entry(frame, textvariable=var_e[-1], width=10, state="normal"))
widget_e[-1].grid(row=0, column=2, columnspan=1, padx=5, pady=5, sticky="ns")
var_e.append(tk.StringVar(master=frame, value='B'))
widget_e.append(tk.Entry(frame, textvariable=var_e[-1], width=10, state="normal"))
widget_e[-1].grid(row=0, column=3, columnspan=1, padx=5, pady=5, sticky="ns")
# set initial entry state
if var_c.get():
widget_e[-1]['state'] = 'normal'
else:
widget_e[-1]['state'] = 'disabled'
# checkbox - binding
widget_c.bind("<ButtonRelease>", lambda event: set_entry_status(event, var_c, widget_e))
root = tk.Tk()
root.title('My Window')
CustomWidget(root, 'name', 'unit')
root.mainloop()
Indeed you can use command kwarg like I suggested in my other answer. In that case event must be removed from the arguments of your callback function:
import tkinter as tk
def set_entry_status(var, widg):
print(var.get())
if var.get():
widg[-1]['state'] = 'normal'
else:
widg[-1]['state'] = 'disabled'
def CustomWidget(frame, name, unit, ):
var_e = []
widget_e = []
var_c = tk.IntVar(master=frame, value=0)
widget_c = tk.Checkbutton(master=frame, text='', variable=var_c, command=lambda: set_entry_status(var_c, widget_e))
widget_c.grid(row=0, column=0, columnspan=1, padx=5, pady=5, sticky="ns")
label_l = name + " (" + unit + ")" # nome + unità di misura in parentesi per GUI
widget_l = tk.Label(frame, text=label_l, padx=1, pady=1)
widget_l.grid(row=0, column=1, columnspan=1, padx=5, pady=5, sticky="wns")
var_e.append(tk.StringVar(master=frame, value='A'))
widget_e.append(tk.Entry(frame, textvariable=var_e[-1], width=10, state="normal"))
widget_e[-1].grid(row=0, column=2, columnspan=1, padx=5, pady=5, sticky="ns")
var_e.append(tk.StringVar(master=frame, value='B'))
widget_e.append(tk.Entry(frame, textvariable=var_e[-1], width=10, state="normal"))
widget_e[-1].grid(row=0, column=3, columnspan=1, padx=5, pady=5, sticky="ns")
# set initial entry state
if var_c.get():
widget_e[-1]['state'] = 'normal'
else:
widget_e[-1]['state'] = 'disabled'
root = tk.Tk()
root.title('My Window')
CustomWidget(root, 'name', 'unit')
root.mainloop()
I am trying to create an employee web app. I have created the home page, login page and application page. The application page gets the details of the candidates who want to apply for a job.
I have used tkcalendar module for selecting 'expected start date'. The GUI works fine but I am not able to get the value of the date selected.
I tried to use get_date() but it shows the following error:
self.date = self.choose_date.get_date()
AttributeError: 'Button' object has no attribute 'get_date'
This is the code I executed.
import tkinter as tk
from tkinter import ttk
import mysql.connector
from tkcalendar import *
class ABCApp(tk.Tk):
BKGR_IMAGE_PATH = 'images\\bg5.png'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.geometry("1500x750")
main_frame = tk.Frame(self,width=200,height=50,highlightbackground="black",highlightthickness=1,background = "#e6ffe6")
main_frame.pack(side='top', fill='both', expand='True')
main_frame.grid_rowconfigure(0, weight=1)
main_frame.grid_columnconfigure(0, weight=1)
self.bkgr_image = tk.PhotoImage(file=self.BKGR_IMAGE_PATH)
self.frames = {}
for F in (HomePage,LogIn,PersonalPage,ApplicationPage):
frame = F(main_frame, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky='nsew')
self.show_frame(HomePage)
def show_frame(self,container):
frame = self.frames[container]
frame.tkraise()
class BasePage(tk.Frame):
def __init__(self, parent, controller):
super().__init__(parent)
label_bkgr = tk.Label(self, image=controller.bkgr_image)
label_bkgr.place(x=0,y=0) # Center label w/image.
class HomePage(BasePage):
def __init__(self, parent, controller):
super().__init__(parent, controller)
label = ttk.Label(self, text='Home Page', font =("Helvetica",20))
label.pack(padx=10, pady=10)
button1 = ttk.Button(self, text="Log In",
command=lambda: controller.show_frame(LogIn))
button1.pack()
class LogIn(BasePage):
def __init__(self,parent,controller):
super().__init__(parent, controller)
login_frame = tk.Frame(self, width=200, height=50, background="white")
login_frame.grid(row=400, column=20, padx=500, pady=250)
self.label_title = tk.Label(login_frame, text="Log In", font=("Helvetica", 40), bg="white")
self.label_title.grid(row=0, column=20, padx=10, pady=10)
self.label_username = tk.Label(login_frame, text="Username", font=("Helvetica", 20), bg="white")
self.label_username.grid(row=50, column=20, padx=10, pady=10)
self.entry_username = tk.Entry(login_frame, width=15, font=("Helvetica", 20), bd=3)
self.entry_username.grid(row=50, column=30, padx=10, pady=10)
self.label_password = tk.Label(login_frame, text="Password", font=("Helvetica", 20), bg="white")
self.label_password.grid(row=60, column=20, padx=10, pady=10)
self.entry_password = tk.Entry(login_frame, width=15, font=("Helvetica", 20), bd=3)
self.entry_password.grid(row=60, column=30, padx=10, pady=10)
self.login_button = tk.Button(login_frame, text="Log In",command=lambda: [self.submit(),controller.show_frame(PersonalPage)],font=("Helvetica", 20),bg="white")
self.login_button.grid(row=70, column=25, padx=10, pady=10)
def submit(self):
self.u_name = self.entry_username.get()
self.p_word = self.entry_password.get()
employee = mysql.connector.connect(host="localhost", user="root", password="", database="edatabase")
cursor_variable = employee.cursor()
cursor_variable.execute("INSERT INTO login VALUES ('" + self.u_name + "','" + self.p_word + "')")
employee.commit()
employee.close()
class PersonalPage(BasePage):
def __init__(self, parent, controller):
super().__init__(parent, controller)
personal_frame = tk.Frame(self, width=200, height=100, background="white")
personal_frame.grid(row=50, column=150, padx=300, pady=100)
personal_details_frame = tk.Frame(personal_frame,width =150,height =50,background="#e6ffe6")
personal_details_frame.grid(row =55,column =0,padx = 50,pady = 50)
self.label_title = tk.Label(personal_details_frame, text="Personal Details",font=("Helvetica", 20),bg ="#e6ffe6")
self.label_title.grid(row=10, column=0, sticky='W')
self.label_name = tk.Label(personal_details_frame, text="Name",font=("Helvetica", 12),bg ="#e6ffe6")
self.label_name.grid(row=15, column=0, padx=10, pady=10, sticky='W')
self.entry_name = tk.Entry(personal_details_frame,bd=3, font=("Helvetica", 12), width=50)
self.entry_name.grid(row=15, column=10, padx=10, pady=10, sticky='W')
self.label_email = tk.Label(personal_details_frame, text="Email id", font=("Helvetica", 12),bg ="#e6ffe6")
self.label_email.grid(row=30, column=0, padx=10, pady=10, sticky='W')
self.entry_email = tk.Entry(personal_details_frame, bd=3, font=("Helvetica", 12), width=50)
self.entry_email.grid(row=30, column=10, padx=10, pady=10, sticky='W')
self.label_mobilenumber = tk.Label(personal_details_frame, text="Mobile Number",font=("Helvetica", 12),bg ="#e6ffe6")
self.label_mobilenumber.grid(row=45, column=0, padx=10, pady=10, sticky='W')
self.entry_mobile = tk.Entry(personal_details_frame,bd=3, font=("Helvetica", 12), width=50)
self.entry_mobile.grid(row=45, column=10, padx=10, pady=10, sticky='W')
self.label_address = tk.Label(personal_details_frame, text="Address",font=("Helvetica", 12),bg ="#e6ffe6")
self.label_address.grid(row=60, column=0, padx=10, pady=10, sticky='W')
self.text_address = tk.Text(personal_details_frame,bd=3, font=("Helvetica", 12), width=50, height=5)
self.text_address.grid(row=60, column=10, padx=10, pady=10, sticky='W')
self.button_next = tk.Button(personal_details_frame,text = "Next",font = ("Helvetica",12),bg ="#b3ccff",command=lambda: [self.personal_next(),controller.show_frame(ApplicationPage)])
self.button_next.grid(row = 70,column =20,padx=10,pady=10,sticky='W')
def personal_next(self):
self.name = self.entry_name.get()
self.email = self.entry_email.get()
self.mobile = self.entry_mobile.get()
self.address = self.text_address.get("1.0","end-1c")
employee = mysql.connector.connect(host="localhost", user="root", password="", database="edatabase")
cursor_variable = employee.cursor()
cursor_variable.execute("INSERT INTO personal VALUES ('" + self.name + "','" + self.email + "','" + self.mobile + "','" + self.address + "')")
employee.commit()
employee.close()
class ApplicationPage(BasePage):
def __init__(self, parent, controller):
super().__init__(parent, controller)
application_frame = tk.Frame(self, width=200, height=100, background="white")
application_frame.grid(row=50, column=150, padx=300, pady=100)
application_details_frame = tk.Frame(application_frame, width=150, height=50, background="#e6ffe6")
application_details_frame.grid(row=55, column=0, padx=50, pady=50)
self.label_title = tk.Label(application_details_frame, text="Application Details", font=("Helvetica", 20),bg="#e6ffe6")
self.label_title.grid(row=10, column=0, sticky='W')
self.label_position = tk.Label(application_details_frame, text="Applied for Position", font=("Helvetica", 12),bg ="#e6ffe6")
self.label_position.grid(row=75, column=0, padx=10, pady=10, sticky='W')
self.list_box1 = tk.Listbox(application_details_frame, width=50, height=3, font=("Helvetica", 12))
self.list_box1.insert(1, "Database Admin")
self.list_box1.insert(2, "Network Admin")
self.list_box1.insert(3, "Deployment Admin")
self.list_box1.grid(row=75, column=10, padx=10, pady=10, sticky='w')
self.label_date = tk.Label(application_details_frame, text="Expected Start Date", font=("Helvetica", 12),bg ="#e6ffe6")
self.label_date.grid(row=90, column=0, padx=10, pady=10, sticky='W')
self.choose_date = tk.Button(application_details_frame, text="Choose Available Date", command=lambda: self.open_calendar(), width=49, bg="white",font=("Helvetica", 12), anchor='w')
self.choose_date.grid(row=90, column=10, padx=10, pady=10, sticky='w')
self.label_proficiency = tk.Label(application_details_frame, text="Proficient Language", font=("Helvetica", 12),bg ="#e6ffe6")
self.label_proficiency.grid(row=120, column=0, padx=10, pady=10, sticky='W')
self.radio = tk.IntVar()
self.radio_button1 = tk.Radiobutton(application_details_frame, text="Java", variable=self.radio, value=1, font=("Helvetica", 12),bg ="#e6ffe6")
self.radio_button1.grid(row=120, column=10, padx=10, pady=10, sticky='w')
self.radio_button2 = tk.Radiobutton(application_details_frame, text="SQL", variable=self.radio, value=2, font=("Helvetica", 12),bg ="#e6ffe6")
self.radio_button2.grid(row=135, column=10, padx=10, pady=10, sticky='w')
self.radio_button3 = tk.Radiobutton(application_details_frame, text="C", variable=self.radio, value=3, font=("Helvetica", 12),bg ="#e6ffe6")
self.radio_button3.grid(row=150, column=10, padx=10, pady=10, sticky='w')
self.submit_button = tk.Button(application_details_frame,text = "Submit",command = self.submit(),font = ("Helvetica",12),bg ="#b3ccff")
self.submit_button.grid(row = 220,column =10,padx=10,pady=10,sticky='W')
def submit(self):
self.position = self.list_box1.get(tk.ANCHOR)
self.date = self.choose_date.get_date()
employee = mysql.connector.connect(host="localhost", user="root", password="", database="edatabase")
cursor_variable = employee.cursor()
cursor_variable.execute("INSERT INTO application VALUES ('" + self.position + "','"+self.date+"')")
employee.commit()
employee.close()
def open_calendar(self):
self.toplevel1 = tk.Toplevel(self)
self.calendar_variable = Calendar(self.toplevel1, selectmode="day", year=2021, month=4, day=10)
self.calendar_variable.pack()
self.toplevel1.mainloop()
app = ABCApp()
app.mainloop()
Any help is appreciated.
First the following line:
self.submit_button = tk.Button(application_details_frame,text = "Submit",command = self.submit(),font = ("Helvetica",12),bg ="#b3ccff")
will execute self.submit() immediately. It should be:
self.submit_button = tk.Button(application_details_frame, text="Submit", command=self.submit, font=("Helvetica",12), bg="#b3ccff")
Second as the error said, self.choose_date is a tk.Button not tkcalendar.Calendar. Better create an instance variable of tk.StringVar and associate it to the tkcalendar.Calendar widget. Then you can use this instance variable to get the selected date:
class ApplicationPage(BasePage):
def __init__(self, parent, controller):
...
self.selected_date = tk.StringVar()
def submit(self):
self.position = self.list_box1.get(tk.ANCHOR)
self.date = self.selected_date.get() # get the selected date
...
def open_calendar(self):
...
self.calendar_variable = Calendar(self.toplevel1, selectmode="day", year=2021, month=4, day=10,
textvariable=self.selected_date)
...
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?
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()
I am trying to add a configuration window in my coupled oscillator simulation. But when I want to get the value of tkinter variables to set up the system, I only get ''.
I tried to change the type from tk.DoubleVar() to tk.StringVar() but nothing seems to works...
Here the code for the configuration frame for one object. Then I create two of them and add them to the configuration frame.
import tkinter as tk
class MassConfig(tk.Frame):
def __init__(self, root, **kwargs):
tk.Frame.__init__(self, root, kwargs)
self.grid()
# Variables :
self.weight = tk.StringVar()
self.vitesse = tk.StringVar()
self.position = tk.StringVar()
self.lbl_weight = tk.Label(self, text='Masse :')
self.lbl_weight.grid(row=0, column=0)
self.entry_weight = tk.Entry(self, textvariable=self.weight, width=5)
self.entry_weight.grid(row=0, column=1)
self.lbl_vit = tk.Label(self, text='Vitesse :')
self.lbl_vit.grid(row=1, column=0, pady=5)
self.entry_vit = tk.Entry(self, textvariable=self.vitesse, width=5)
self.entry_vit.grid(row=1, column=1)
self.lbl_pos = tk.Label(self, text='Position :')
self.lbl_pos.grid(row=2, column=0)
self.entry_pos = tk.Entry(self, textvariable=self.position, width=5)
self.entry_pos.grid(row=2, column=1)
Here the code of the configuration frame, which has two 'MassConfig' frame inside.
import tkinter as tk
from gui.masse_config import MassConfig
class Configuration(tk.Frame):
def __init__(self, root, **kwargs):
tk.Frame.__init__(self, root, **kwargs)
self.root = root
self.grid()
self.update()
self.is_alive = True
self.data = {}
self.m1_frame = tk.LabelFrame(self, text='Masse 1', width=200, height=200)
self.m1_frame.grid(column=0, row=0, padx=(10, 5), pady=(10, 10))
self.m2_frame = tk.LabelFrame(self, text='Masse 2', width=200, height=200)
self.m2_frame.grid(column=1, row=0, padx=(5, 10), pady=(10, 10))
self.config_1 = MassConfig(self.m1_frame)
self.config_2 = MassConfig(self.m2_frame)
self.config_1.grid(padx=10, pady=10)
self.config_2.grid(padx=10, pady=10)
self.btn_validation = tk.Button(self, text='Valider', command=self.validation)
self.btn_validation.grid(row=3, column=1, padx=10, pady=(0, 10), sticky=tk.E)
self.update()
def validation(self):
print(":", self.config_1.position.get())
self.data['Mass 1'] = {}
self.data['Mass 1']['Position'] = self.config_1.position.get()
self.data['Mass 1']['Vitesse'] = self.config_1.vitesse.get()
self.data['Mass 1']['Masse'] = self.config_1.weight.get()
self.data['Mass 2'] = {}
self.data['Mass 2']['Position'] = self.config_2.position.get()
self.data['Mass 2']['Vitesse'] = self.config_2.vitesse.get()
self.data['Mass 2']['Masse'] = self.config_2.weight.get()
self.is_alive = False
self.root.destroy()
I want to have the value of the tkinter variables self.weight, self.vitesse and self.position from the MassConfig class in a dictionary (self.data from Configuration class). But nothing come out, except ''.