Tkinter won't close correctly and launch new file - python

I made a little login screen. After I put in the credentials I want the Tkinter to be closed and open a new python file. If you execute the code below it will give me the error NameError: name ttk is not defined. In the other file I imported everything and gave it the correct name.
The file I use for the login:
from tkinter import *
import tkinter.messagebox as tm
class LoginFrame(Frame):
def __init__(self, master):
super().__init__(master)
self.label_username = Label(self, text="Username")
self.label_password = Label(self, text="Password")
self.photo = PhotoImage(file="sbshreg.png")
self.label_image = Label(root, image=self.photo)
self.label_image.image = self.photo
self.entry_username = Entry(self)
self.entry_password = Entry(self, show="*")
self.label_username.grid(row=0, sticky=E)
self.label_password.grid(row=1, sticky=E)
self.label_image.grid(row=3, column=2, rowspan=2, columnspan=2, sticky=W, padx=10)
self.entry_username.grid(row=0, column=1, sticky=E)
self.entry_password.grid(row=1, column=1, sticky=E)
self.logbtn = Button(self, text="Login", command=self._login_btn_clicked)
self.logbtn.grid(columnspan=2, column=1, row=2, sticky=S+E+N+W)
self.grid()
def _login_btn_clicked(self):
username = self.entry_username.get()
password = self.entry_password.get()
if username == "123" and password == "123":
tm.showinfo("SBSHREG", "Welcome 123")
#The sweet spot where all goes wrong...
self.destroy()
exec(open("./BatchFrame.py").read())
else:
tm.showerror("SBSHREG", "Incorrect username")
root = Tk()
root.title("SBSHREG")
root.geometry("235x120")
lf = LoginFrame(root)
root.mainloop()
In the other file I got this: from tkinter import ttk as ttk which should prevent the error in the other file from happening.
from tkinter import *
import tkinter.messagebox as tm
from tkinter import ttk as ttk
class BatchFrame(Frame):
def __init__(self, master):
super().__init__(master)
self.photo = PhotoImage(file="sbshreg.png")
self.label_photo = Label(root, image=self.photo)
self.label_photo.image = self.photo
self.label_photo.grid(row=0, column=2, sticky=N, padx=10, pady=10)
#Add frame starting here
frame = LabelFrame(self.master, text='Voeg batch toe')
frame.grid (row=0, column=0, padx=10)
self.label_batch = Label(frame, text="Batchnummer")
self.label_employee = Label(frame, text="Medewerker")
self.label_material = Label(frame, text="Materiaalsoort")
self.label_weight = Label(frame, text="Gewicht")
self.entry_batch = Entry(frame)
self.entry_employee = Entry(frame)
self.entry_material= Entry(frame)
self.entry_weight = Entry(frame)
self.label_batch.grid(row=0, column=0, sticky=S+E+N+W, columnspan=2, padx=10)
self.label_employee.grid(row=2, column=0, sticky=S+E+N+W, columnspan=2, padx=10)
self.label_material.grid(row=4, column=0, sticky=S+E+N+W, columnspan=2, padx=10)
self.label_weight.grid(row=6, column=0, sticky=S+E+N+W, columnspan=2, padx=10)
self.entry_batch.grid(row=1, column=0, sticky=S+E+N+W, columnspan=2, padx=10)
self.entry_employee.grid(row=3, column=0, sticky=S+E+N+W, columnspan=2, padx=10)
self.entry_material.grid(row=5, column=0, sticky=S+E+N+W, columnspan=2, padx=10)
self.entry_weight.grid(row=7, column=0, sticky=S+E+N+W, columnspan=2, padx=10)
self.btnadd = Button(frame, text='Voeg toe', command=self._btn_add_clicked)
self.btnadd.grid(column=0, row=8, pady=10)
#Search frame starting here
framesearch = LabelFrame(self.master, text='Zoek')
framesearch.grid(row=0, column=1, sticky=N)
self.label_batch = Label(framesearch, text="Batchnummer")
self.label_employee = Label(framesearch, text="Medewerker")
self.entry_batch = Entry(framesearch)
self.entry_employee = Entry(framesearch)
self.label_batch.grid(row=0, column=0, sticky=S, columnspan=2, padx=10)
self.label_employee.grid(row=2, column=0, sticky=S, columnspan=2, padx=10)
self.entry_batch.grid(row=1, column=0, sticky=S + E + N + W, columnspan=2, padx=10, pady=10)
self.entry_employee.grid(row=3, column=0, sticky=S + E + N + W, columnspan=2, padx=10, pady=10)
self.btnbatch = Button(framesearch, text="Zoek", command=self._btn_batch_clicked)
self.btnemployee = Button(framesearch, text="Zoek", command=self._btn_employee_clicked)
self.btnbatch.grid(columnspan=1, column=2, row=1, sticky=W, padx=10)
self.btnemployee.grid(columnspan=1, column=2, row=3, sticky=W, padx=10)
#This is the viewingarea for the data
self.tree = ttk.Treeview (height=10, columns=("Batchnummer", "Medewerker", "Materiaalsoort", "Gewicht"))
self.tree.grid (row=9, columnspan=10, padx=10, pady=10)
self.tree.heading('#1', text='Batchnummer', anchor=W)
self.tree.heading('#2', text='Medewerker', anchor=W)
self.tree.heading('#3', text='Materiaalsoort', anchor=W)
self.tree.heading('#4', text='Gewicht', anchor=W)
self.tree.column('#0', stretch=NO, minwidth=0, width=0)
self.tree.column('#1', stretch=NO, minwidth=0, width=100)
self.tree.column('#2', stretch=NO, minwidth=0, width=100)
self.tree.column('#3', stretch=NO, minwidth=0, width=100)
self.tree.column('#4', stretch=NO, minwidth=0, width=100)
self.grid()
def _btn_add_clicked(self):
batch = self.entry_batch.get()
def _btn_batch_clicked(self):
batch = self.entry_batch.get()
def _btn_employee_clicked(self):
batch = self.entry_employee.get()
root = Tk()
root.title("SBSHREG")
root.geometry("432x480")
lf = BatchFrame(root)
root.mainloop()
If I change self.destroy() to root.destroy() I get the following error: _tkinter.TclError: can't invoke "label" command: application has been destroyed. In the second file the functions are not done yet because I'm still working on the file, but this shouldn't have any impact on the error.
I searched everywhere and tried a lot and I still got no clue whatsoever...

Consider initializing frames in a top level class, GUI, that handles opening of both frames where LoginFrame calls its parent's open_batch() (now lambda implemented) method. Below assumes LoginFrame.py and BatchFrame.py resides in same folder as GUI_App script.
In this way, scripts run as standalone modules on one Tk() instance.
GUIApp (calls child frames, LoginFrame, and BatchFrame)
from tkinter import *
import LoginFrame as LF
import BatchFrame as BF
class GUI():
def __init__(self):
self.root = Tk()
self.root.title("SBSHREG")
self.root.geometry("235x120")
self.root.open_batch = self.open_batch
lf = LF.LoginFrame(self.root)
self.root.mainloop()
def open_batch(self):
bf = BF.BatchFrame(self.root)
app = GUI()
LoginFrame
from tkinter import *
import tkinter.messagebox as tm
class LoginFrame(Frame):
def __init__(self, master):
super().__init__(master)
self.label_username = Label(self, text="Username")
self.label_password = Label(self, text="Password")
self.photo = PhotoImage(file="sbshreg.png")
self.label_image = Label(self, image=self.photo)
self.label_image.image = self.photo
self.entry_username = Entry(self)
self.entry_password = Entry(self, show="*")
self.label_image.grid(row=0, column=2, rowspan=2, columnspan=2, sticky=W, padx=10)
self.label_username.grid(row=2, sticky=E)
self.label_password.grid(row=3, sticky=E)
self.entry_username.grid(row=2, column=1, sticky=E)
self.entry_password.grid(row=3, column=1, sticky=E)
self.logbtn = Button(self, text="Login", command=lambda: self._login_btn_clicked(master))
self.logbtn.grid(row=4, column=1, columnspan=2, sticky=S+E+N+W)
self.grid()
def _login_btn_clicked(self, controller):
username = self.entry_username.get()
password = self.entry_password.get()
if username == "123" and password == "123":
tm.showinfo("SBSHREG", "Welcome 123")
self.destroy()
controller.open_batch()
else:
tm.showerror("SBSHREG", "Incorrect username")
BatchFrame
from tkinter import *
import tkinter.messagebox as tm
from tkinter import ttk as ttk
class BatchFrame(Frame):
def __init__(self, master):
super().__init__(master)
self.photo = PhotoImage(file="sbshreg.png")
self.label_photo = Label(master, image=self.photo)
self.label_photo.image = self.photo
self.label_photo.grid(row=0, column=2, sticky=N, padx=10, pady=10)
#Add frame starting here
frame = LabelFrame(master, text='Voeg batch toe')
frame.grid (row=0, column=0, padx=10)
self.label_batch = Label(frame, text="Batchnummer")
self.label_employee = Label(frame, text="Medewerker")
self.label_material = Label(frame, text="Materiaalsoort")
self.label_weight = Label(frame, text="Gewicht")
self.entry_batch = Entry(frame)
self.entry_employee = Entry(frame)
self.entry_material= Entry(frame)
self.entry_weight = Entry(frame)
self.label_batch.grid(row=0, column=0, sticky=S+E+N+W, columnspan=2, padx=10)
self.label_employee.grid(row=2, column=0, sticky=S+E+N+W, columnspan=2, padx=10)
self.label_material.grid(row=4, column=0, sticky=S+E+N+W, columnspan=2, padx=10)
self.label_weight.grid(row=6, column=0, sticky=S+E+N+W, columnspan=2, padx=10)
self.entry_batch.grid(row=1, column=0, sticky=S+E+N+W, columnspan=2, padx=10)
self.entry_employee.grid(row=3, column=0, sticky=S+E+N+W, columnspan=2, padx=10)
self.entry_material.grid(row=5, column=0, sticky=S+E+N+W, columnspan=2, padx=10)
self.entry_weight.grid(row=7, column=0, sticky=S+E+N+W, columnspan=2, padx=10)
self.btnadd = Button(frame, text='Voeg toe', command=self._btn_add_clicked)
self.btnadd.grid(column=0, row=8, pady=10)
#Search frame starting here
framesearch = LabelFrame(master, text='Zoek')
framesearch.grid(row=0, column=1, sticky=N)
self.label_batch = Label(framesearch, text="Batchnummer")
self.label_employee = Label(framesearch, text="Medewerker")
self.entry_batch = Entry(framesearch)
self.entry_employee = Entry(framesearch)
self.label_batch.grid(row=0, column=0, sticky=S, columnspan=2, padx=10)
self.label_employee.grid(row=2, column=0, sticky=S, columnspan=2, padx=10)
self.entry_batch.grid(row=1, column=0, sticky=S + E + N + W, columnspan=2, padx=10, pady=10)
self.entry_employee.grid(row=3, column=0, sticky=S + E + N + W, columnspan=2, padx=10, pady=10)
self.btnbatch = Button(framesearch, text="Zoek", command=self._btn_batch_clicked)
self.btnemployee = Button(framesearch, text="Zoek", command=self._btn_employee_clicked)
self.btnbatch.grid(columnspan=1, column=2, row=1, sticky=W, padx=10)
self.btnemployee.grid(columnspan=1, column=2, row=3, sticky=W, padx=10)
#This is the viewingarea for the data
self.tree = ttk.Treeview (height=10, columns=("Batchnummer", "Medewerker", "Materiaalsoort", "Gewicht"))
self.tree.grid (row=9, columnspan=10, padx=10, pady=10)
self.tree.heading('#1', text='Batchnummer', anchor=W)
self.tree.heading('#2', text='Medewerker', anchor=W)
self.tree.heading('#3', text='Materiaalsoort', anchor=W)
self.tree.heading('#4', text='Gewicht', anchor=W)
self.tree.column('#0', stretch=NO, minwidth=0, width=0)
self.tree.column('#1', stretch=NO, minwidth=0, width=100)
self.tree.column('#2', stretch=NO, minwidth=0, width=100)
self.tree.column('#3', stretch=NO, minwidth=0, width=100)
self.tree.column('#4', stretch=NO, minwidth=0, width=100)
self.grid()
def _btn_add_clicked(self):
batch = self.entry_batch.get()
def _btn_batch_clicked(self):
batch = self.entry_batch.get()
def _btn_employee_clicked(self):
batch = self.entry_employee.get()

I do not agree with the method of how you are invoking your 2nd python file.
You really dont need to use exec here.
However if you really want to you need to add import tkinter.ttk as ttk to your first page for it to work right.
Your best option is to import the 2nd file on the 1st file and invoke it by calling the class name.
so for you imports on the first page you need to add import BatchFrame.
Then call it in your code.
Replace:
exec(open("./test2.py").read())
with:
BatchFrame.BatchFrame(root)
I do see one mistake in your BatchFrame class thought.
change this:
self.label_photo = Label(root, image=self.photo)
to this:
self.label_photo = Label(master, image=self.photo)
UPDATE:
To address your issue from the comment make these changes:
1: Add this to your BatchFrame Class:
class BatchFrame(Frame):
def __init__(self, master):
super().__init__(master)
self.master = master # add this
self.master.title("SBSHREG") # and this
self.master.geometry("432x480") # and this
2: Remove this from your BatchFrame file:
root = Tk()
root.title("SBSHREG")
root.geometry("432x480")
lf = BatchFrame(root)
root.mainloop()
3: Add this to your LoginFrame class:
class LoginFrame(Frame):
def __init__(self, master):
super().__init__(master)
self.master = master # add this
4: In the LoginFrame class change this:
BatchFrame.BatchFrame(root)
to this:
BatchFrame.BatchFrame(self.master)

I recommend importing batchframe instead of executing it.
from tkinter import *
import tkinter.messagebox as tm
from tkinter import ttk as ttk
from batchframe import BatchFrame
class LoginFrame(Frame):
def __init__(self, master):
super().__init__(master)
self.master = master
self.label_username = Label(self, text="Username")
self.label_password = Label(self, text="Password")
self.photo = PhotoImage(file="icon.png")
self.label_image = Label(root, image=self.photo)
self.label_image.image = self.photo
self.entry_username = Entry(self)
self.entry_password = Entry(self, show="*")
self.label_username.grid(row=0, sticky=E)
self.label_password.grid(row=1, sticky=E)
self.label_image.grid(row=3, column=2, rowspan=2, columnspan=2, sticky=W, padx=10)
self.entry_username.grid(row=0, column=1, sticky=E)
self.entry_password.grid(row=1, column=1, sticky=E)
self.logbtn = Button(self, text="Login", command=self._login_btn_clicked)
self.logbtn.grid(columnspan=2, column=1, row=2, sticky=S+E+N+W)
self.grid()
def _login_btn_clicked(self):
username = self.entry_username.get()
password = self.entry_password.get()
if username == "123" and password == "123":
tm.showinfo("SBSHREG", "Welcome 123")
#The sweet spot where all goes wrong...
self.destroy()
# Create the instance of the BatchFrame class, passing in self.master
self.batchframe = BatchFrame(self.master)
else:
tm.showerror("SBSHREG", "Incorrect username")
Then in batchframe.py change variable reference from root to master

Related

trying to have my GUI give an error message when one of the fields are not put in?

trying to have my GUI give an error message when one of the fields are not put in ? im struggling to see how to do have a message pop up when one of the fields are not put in but when they are all put in then it works.
from numbers import Number
import tkinter
from tkinter import ttk
from tkinter import messagebox
def enter_data():
accepted = accept_var.get()
if accepted=="Accepted":
Cardnumber = Card_number_entry.get()
Year = Year_entry.get()
Name = Name_entry.get()
Set = Set_entry.get()
Cert = Cert_entry.get()
Grade = Grade_entry.get()
print("Card Number:", Cardnumber)
print("Year:", Year)
print("Name:", Name)
print("Set:", Set)
print("Cert:", Cert)
print("Grade", Grade)
else:
tkinter.messagebox.showwarning(title= "Error", message="You have missed out infomation")
window = tkinter.Tk()
window.title("MGC POPULATION REPORT")
frame = tkinter.Frame(window)
frame.pack()
card_info_frame =tkinter.LabelFrame(frame, text="Card Infomation")
card_info_frame.grid(row= 0, column=0, padx=40, pady=20)
Card_number_label = tkinter.Label(card_info_frame, text="Card Number")
Card_number_label.grid(row=0, column=0, padx=10, pady=1)
Year_label = tkinter.Label(card_info_frame, text="Year")
Year_label.grid(row=2, column=0, padx=10, pady=1)
Name_label = tkinter.Label(card_info_frame, text="Name")
Name_label.grid(row=4, column=0, padx=10, pady=1)
Set_label = tkinter.Label(card_info_frame, text="Set")
Set_label.grid(row=6, column=0, padx=10, pady=1)
Cert_label = tkinter.Label(card_info_frame, text="Certification (#)")
Cert_label.grid(row=8, column=0, padx=10, pady=1)
Grade_label = tkinter.Label(card_info_frame, text="Grade")
Grade_label.grid(row=10, column=0, padx=10, pady=1)
Card_number_entry = tkinter.Entry(card_info_frame)
Year_entry = tkinter.Entry(card_info_frame)
Name_entry = tkinter.Entry(card_info_frame)
Set_entry = tkinter.Entry(card_info_frame)
Cert_entry = tkinter.Entry(card_info_frame)
Grade_entry = tkinter.Entry(card_info_frame)
Card_number_entry.grid(row=1, column=0)
Year_entry.grid(row=3, column=0)
Name_entry.grid(row=5, column=0)
Set_entry.grid(row=7, column=0)
Cert_entry.grid(row=9, column=0)
Grade_entry.grid(row=11, column=0)
button = tkinter.Button(frame, text="Enter Data", command= enter_data)
button.grid(row=13, column=0, sticky="news", padx=20, pady=10)
window.mainloop()
so if anyone can help me that would be helpful thank you
You can check if the text boxes are empty.
For example:
if not Card_number_entry.get() or not Name_entry.get() or not Set_entry.get() or not Cert_entry.get() or not Grade_entry.get():
accepted = "Error"
else:
accepted = "Accepted"
If any of the textboxes have no content, the if statement will return true.

How to make python tkinter treeview widget to fill empty row and column spaces on grid?

I have a window to display multiple treeview widgets. Currently there are some empty row spaces below the treeview when I expand it and I'm not sure on how to fill the empty spaces below dynamically when I expand the window. I have tried adjusting the rowspan/columnspan options but could not get the desired output as described in image below. I have also included a reproduceable code below for testing my program. Please help to advise on which part I need to make changes. Thanks!
import shutil
import tkinter as tk
import tkinter.ttk as ttk
import tempfile
import zipfile, re, os
from tkinter import *
from tkinter import filedialog
from pathlib import Path
import tkinter.messagebox
from fpdf import FPDF
from datetime import datetime, timedelta
import ctypes
DEPTH = 2
EXCLUDES = {'__MACOSX', 'resources'}
class HomePage(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
self.notebook = ttk.Notebook() # Create a notebook widget
self.add_tab1()
self.notebook.grid(row=0)
self.notebook.pack(expand=1, fill="both")
def add_tab1(self):
tab1 = tab_one(self.notebook)
self.notebook.add(tab1, text="Home")
class data_table(object):
def __init__(self, site, panels_count, tev_count):
self.site = site
self.panels_count = panels_count
self.tev_count = tev_count
class tab_one(Frame):
def __init__(self, *args, **kwargs):
Frame.__init__(self, *args, **kwargs)
# Creating frames on the window/canvas for the first tab
frame_selectfile = tk.LabelFrame(self, text="Step 1: Zip File Extraction ", bd=6) # Frame1 on the window/canvas
frame_selectfile.grid(column=0, row=0, padx=10, pady=10, sticky='NSEW') # Positioning frame1
frame_selectfile.configure(borderwidth=1)
self.grid_columnconfigure(1, weight=1) # Configuring the column for the main window/canvas
self.grid_rowconfigure(1, weight=1) # Configuring the row for the main window/canvas
frame_checkpd = tk.LabelFrame(self, text="Step 2: Check PD ", bd=6) # Frame2 on the window/canvas
frame_checkpd.grid(column=1, row=0, padx=10, pady=10, sticky='NSEW') # Positioning frame2
frame_checkpd.configure(borderwidth=1)
self.grid_columnconfigure(1, weight=1) # Configuring the column for the main window/canvas
self.grid_rowconfigure(1, weight=1) # Configuring the row for the main window/canvas
#Frame to display data in treeview
frame_tree = tk.LabelFrame(self, text="PD Results ", bd=6) # Frame2 on the window/canvas
frame_tree.grid(column=0, row=1, columnspan=2, rowspan=2, padx=10, pady=10, sticky='NSEW') # Positioning frame2
frame_tree.configure(borderwidth=1)
self.grid_columnconfigure(1, weight=1) # Configuring the column for the main window/canvas
self.grid_rowconfigure(1, weight=1) # Configuring the row for the main window/canvas
# Initializing all variables in frame_selectfile
file_ID = tk.StringVar()
location_id = tk.StringVar()
unzip_status = tk.StringVar()
tmpdir = tempfile.TemporaryDirectory().name
f_tem_sdir = open(os.getcwd()+"\\temp_dir.txt", "w")
f_tem_sdir.write(tmpdir)
f_tem_sdir.close()
zip_filename = tk.StringVar()
site_id = tk.StringVar()
site_id.set("0")
data_table_list = []
middleframe = tk.LabelFrame(frame_selectfile, bd=5)
databaseView = ttk.Treeview(middleframe, selectmode="browse")
label_filename = tk.Label(frame_selectfile, text=" ", width=10, relief='flat').grid(column=0, row=1, padx=5,
pady=5, sticky='NW')
label_filelocation = tk.Label(frame_selectfile, text="File Location:", width=12, relief='flat').grid(column=0,
row=2,
padx=5,
pady=5,
sticky='NW')
filename_Entry = tk.Label(frame_selectfile, width=52, textvariable=file_ID)
filename_Entry.grid(column=1, row=1, padx=5, pady=5, sticky='NW')
filename_Entry.configure(state='normal')
filelocation_Entry = tk.Entry(frame_selectfile, width=63, textvariable=location_id)
filelocation_Entry.grid(column=1, row=2, padx=5, pady=5, sticky='W')
filelocation_Entry.configure(background='palegreen', foreground='black')
unzip_status.set("")
label_unzipstatus = tk.Label(frame_selectfile, width=20, relief='flat', textvariable=unzip_status)
label_unzipstatus.grid(column=1, row=5, padx=5, pady=5, sticky='NSEW')
selectzip_button = tk.Button(frame_selectfile, width=20, text="Select Zip File",
command=lambda: self.upload_action(location_id, zip_filename, tmpdir))
selectzip_button.grid(column=1, row=3, padx=5, pady=3, ipady=3, sticky='SW')
unzip_button = tk.Button(frame_selectfile, width=20, text="Extract",
command=lambda: self.extract_nested_zip(databaseView, data_table_list,
location_id.get(), tmpdir, zip_filename,
site_id, False))
unzip_button.grid(column=1, row=3, padx=5, pady=3, ipady=3, sticky='NE')
# Creating LabelFrame in frame_unzip
upperframe = tk.LabelFrame(frame_selectfile, bd=0)
frame_selectfile.rowconfigure(0, weight=1)
frame_selectfile.columnconfigure(2, weight=1)
upperframe.grid(column=0, row=6, columnspan=2, sticky='W')
# middleframe = tk.LabelFrame(frame_selectfile, bd=5)
middleframe.configure(borderwidth=1)
frame_selectfile.columnconfigure(2, weight=1)
frame_selectfile.rowconfigure(1, weight=1)
middleframe.grid(column=0, row=7, columnspan=2, sticky="NSEW")
lowerframe = tk.LabelFrame(frame_selectfile, bd=0)
lowerframe.grid(column=0, row=7)
frame_selectfile.columnconfigure(2, weight=1)
frame_selectfile.rowconfigure(2, weight=0)
# Labels in frame_unzip
label18 = tk.Label(upperframe, text="Number of sites:", relief='flat')
label18.grid(column=0, row=0, padx=5, pady=5, sticky='W')
site_Entry = tk.Entry(upperframe, width=61, textvariable=site_id)
site_Entry.grid(column=1, row=0, padx=10, pady=5, sticky='E')
site_Entry.configure(state='normal', background='palegreen', foreground='black')
label_details = tk.Label(upperframe, text=" ", relief='flat')
label_details.grid(column=0, row=2, padx=5, pady=0, sticky='W')
databaseView.columnconfigure(2, weight=1)
databaseView.grid(column=0, row=0, columnspan=2, sticky="NSEW")
# Creating treeview in frame_unzip
vsb = Scrollbar(middleframe, orient="vertical", command=databaseView.yview())
hsb = Scrollbar(middleframe, orient="horizontal")
middleframe.columnconfigure(0, weight=1)
middleframe.rowconfigure(0, weight=1)
databaseView["show"] = "headings"
databaseView["columns"] = ("site", "panels", "tevs")
vsb.configure(command=databaseView.yview)
vsb.grid(column=1, row=0, sticky="NS")
# Treeview column headings
databaseView.heading("site", text="Site")
databaseView.column("site", anchor='w', width=250)
databaseView.heading("panels", text="Number of Panels")
databaseView.column("panels", anchor='center', width=150)
databaseView.heading("tevs", text="Number of TEVs")
databaseView.column("tevs", anchor='center', width=200)
findpd_btn = tk.Button(frame_checkpd, width=20, text="Find PDs",
command=lambda: self.run_pd_model_exe(tmpdir, zip_filename,parent_tree, tree))
findpd_btn.grid(column=0, row=0, padx=5, pady=5, sticky='E')
export_pdf_btn = tk.Button(frame_checkpd, width=20, text="Export to PDF",
command=lambda: self.export_to_pdf(tmpdir, location_id.get()))
export_pdf_btn.grid(column=1, row=0, padx=5, pady=5, sticky='E')
find_files_btn = tk.Button(frame_checkpd, width=20, text="Clear All",
command=lambda: self.clear_all_files(tmpdir,parent_tree,tree,databaseView))
find_files_btn.grid(column=2, row=0, padx=5, pady=5, sticky='W')
scrollbary = Scrollbar(frame_tree, orient=VERTICAL)
scrollbarx = Scrollbar(frame_tree, orient=HORIZONTAL)
parentframe = tk.LabelFrame(frame_checkpd, bd=0)
frame_checkpd.rowconfigure(2, weight=1)
frame_checkpd.columnconfigure(2, weight=1, )
parentframe.grid(column=0, row=1, columnspan=3, sticky='W')
# PARENT TREE
parent_tree = ttk.Treeview(parentframe,
columns=("1", "2",
"3", "4",
"5", "6",
"7", "8"),
selectmode="extended")
parent_tree.grid(row=1, column=0, pady=2, sticky=N + S + E + W)
#self.parent_tree.pack(expand=True, fill='both')
vsbb = Scrollbar(parentframe, orient="vertical", command=parent_tree.yview())
vsbb.configure(command=parent_tree.yview)
vsbb.grid(column=2, row=1, sticky="NS")
parent_tree.heading("#0", text="")
parent_tree.heading("1", text="File ID")
parent_tree.heading("2", text="Date")
parent_tree.heading("3", text="No")
parent_tree.heading("4", text="Engineer")
parent_tree.heading("5", text="Station")
parent_tree.heading("6", text="Voltage (kV)")
parent_tree.heading("7", text="Max dB")
parent_tree.heading("8", text="Max PD (%)")
# parent_tree.heading("8", text = "Panel No")
parent_tree.column('#0', stretch=YES, minwidth=0, width=5, anchor=CENTER)
parent_tree.column('#1', stretch=YES, minwidth=0, width=130, anchor=CENTER)
parent_tree.column('#2', stretch=YES, minwidth=0, width=130, anchor=CENTER)
parent_tree.column('#3', stretch=YES, minwidth=0, width=130, anchor=CENTER)
parent_tree.column('#4', stretch=YES, minwidth=0, width=130, anchor=CENTER)
parent_tree.column('#5', stretch=YES, minwidth=0, width=130, anchor=CENTER)
parent_tree.column('#6', stretch=YES, minwidth=0, width=130, anchor=CENTER)
parent_tree.column('#7', stretch=YES, minwidth=0, width=130, anchor=CENTER)
parent_tree.column('#8', stretch=YES, minwidth=0, width=130, anchor=CENTER)
# CHILD TREE
tree = ttk.Treeview(frame_tree,
columns=("1", "2", "3", "4"
, "5", "6", "7", "8"
, "9"),
selectmode="extended")
#yscrollcommand=scrollbary.set,
#xscrollcommand=scrollbarx.set)
tree.grid(row=0, column=0, pady=2, sticky=N + S + E + W)
# scrollbary.config(command=tree.yview)
# scrollbary.grid(row=0, column=1, pady=2, sticky=N + S)
#
# scrollbarx.config(command=tree.xview)
# scrollbarx.grid(row=2, column=0, sticky=W + E)
tree_vsb = Scrollbar(frame_tree, orient="vertical", command=tree.yview())
tree_hsb = Scrollbar(frame_tree, orient="horizontal")
tree_vsb.configure(command=tree.yview)
tree_vsb.grid(column=1, row=0, sticky="NS")
tree.heading("#0", text="")
tree.heading("1", text="Panel No")
tree.heading("2", text="TEV Name")
tree.heading("3", text="Component")
tree.heading("4", text="Sublocation")
tree.heading("5", text="Phase Ref Lock")
tree.heading("6", text="dB")
tree.heading("7", text="PRPD")
tree.heading("8", text="Pulse Wave")
tree.heading("9", text="PD %")
tree.column('#0', stretch=NO, minwidth=0, width=0, anchor=CENTER)
tree.column('#1', stretch=YES, minwidth=0, width=175, anchor=CENTER)
tree.column('#2', stretch=YES, minwidth=0, width=175, anchor=CENTER)
tree.column('#3', stretch=YES, minwidth=0, width=175, anchor=CENTER)
tree.column('#4', stretch=YES, minwidth=0, width=175, anchor=CENTER)
tree.column('#5', stretch=YES, minwidth=0, width=175, anchor=CENTER)
tree.column('#6', stretch=YES, minwidth=0, width=175, anchor=CENTER)
tree.column('#7', stretch=YES, minwidth=0, width=175, anchor=CENTER)
tree.column('#8', stretch=YES, minwidth=0, width=175, anchor=CENTER)
tree.column('#9', stretch=YES, minwidth=0, width=175, anchor=CENTER)
if __name__ == '__main__':
homePage = HomePage()
homePage.title("Waveform Identifier") # Window title
screen_width = homePage.winfo_screenwidth()
screen_height = homePage.winfo_screenheight()
width = 1600
height = 800
x = (screen_width / 2) - (width / 2)
y = (screen_height / 2) - (height / 2)
homePage.geometry("%dx%d+%d+%d" % (width, height, x, y))
homePage.resizable(1, 1)
homePage.mainloop()
Issues found
Wrong row number on frame_checkpd.rowconfigure(2, weight=1), it should be row 1.
Wrong sticky option on parentframe.grid(column=0, row=1, columnspan=3, sticky='W'), it should be 'NSEW'.
missing parentframe.rowconfigure(...) and parentframe.columnconfigure(...)
missing frame_tree.rowconfigure(...) and frame_tree.columnconfigure(...)
Below is the required changes to achieve it:
class tab_one(Frame):
def __init__(self, *args, **kwargs):
...
parentframe = tk.LabelFrame(frame_checkpd, bd=0)
frame_checkpd.rowconfigure(1, weight=1) ### row 2 -> 1
frame_checkpd.columnconfigure(2, weight=1, )
parentframe.grid(column=0, row=1, columnspan=3, sticky='NSEW') ### 'W' -> 'EW'
# PARENT TREE
parentframe.rowconfigure(1, weight=1) ### added
parentframe.columnconfigure(0, weight=1) ### added
...
# CHILD TREE
frame_tree.rowconfigure(0, weight=1) ### added
frame_tree.columnconfigure(0, weight=1) ### added
...
Result:

Object of Class inheriting LabelFrame doesnt show up (tkinter)

Basically I have a class that inherits from LabelFrame, I want it to show up on the window itself, but I don't see it at all, it doesn't even show up on the window no matter what I do
from tkinter import *
root = Tk()
root['bg'] = 'white'
root.state('zoomed')
class CharacterFrame(LabelFrame):
def __init__(self, master, skin_img, requirement, desc):
super().__init__(master=master, bg='grey29')
self.desc = Label(self, text=desc)
default_char_frame = CharacterFrame(master=root, desc='Default Character.', requirement=0, skin_img='')
default_char_frame.grid(row=0, column=0, sticky='nse')
root.mainloop()
ok, so i was stupid for not implementing the actual code itself, but ill do it now (This isnt actual source code, just the important code, still has same error as actual code):
from tkinter import *
root = Tk()
root['background'] = 'white'
root.state('zoomed')
class SkinFrame(LabelFrame):
def __init__(self, master, skin_img, requirement, desc):
super().__init__(master=master, bg='grey29')
self.desc = Label(self, text=desc)
self.desc.pack()
def show_chars():
button_grid.grid_forget()
skin_lib.grid(row=1, column=0, sticky='nws')
button_skin0 = Button(skin_lib, text="Skin1", relief="flat", width=15, fg="white", bg="darkgrey", command=lambda: show_char_frame(prev, default_char_frame), font=("Arial", 29, "italic"))
button_skin0.grid(row=0, column=0, pady=(0,10))
back = Button(skin_lib, text="Back", width=15, relief="flat", fg="white", bg="maroon", font=("Arial",29,"italic"),
command=lambda: [skin_lib.grid_forget(), button_grid.grid(row=1, column=0, sticky='nws')])
back.grid(row=100, column=0)
def show_char_frame(prev, char_frame):
skin_lib.grid_forget()
default_char_frame.grid(row=1, column=1, sticky='nse')
default_char_frame = SkinFrame(master=root, desc='Default Skin.', requirement=0, skin_img='')
Label(root, text="Game Title", width=68, relief="flat", bg="white", fg="grey", font=("Arial",26,"italic")).grid(row=0, column=0, sticky='n')
button_grid = LabelFrame(root, bg='grey29', relief="groove", pady=10, padx=10)
button_grid.grid(row=1, column=0, sticky='nws')
skin_lib = LabelFrame(root, bg='grey29', relief="groove", pady=10, padx=10)
skins = Button(button_grid, text="Skins", width=15, relief="flat", fg="white", bg="navy", command=show_chars, font=("Arial", 29, "italic"))
skins.grid(row=2, column=0, pady=(0,10))
previous_skinframe
root.mainloop()
you missed to pack() label to add in control
self.desc.pack()
this is complete code
from tkinter import *
root = Tk()
root['bg'] = 'white'
root.state('zoomed')
class CharacterFrame(LabelFrame):
def __init__(self, master, skin_img, requirement, desc):
super().__init__(master=master, bg='grey29')
self.desc = Label(self, text=desc)
self.desc.pack()
default_char_frame = CharacterFrame(master=root, desc='Default Character.', requirement=0, skin_img='')
default_char_frame.grid(row=0, column=0, sticky='nse')
root.mainloop()
in this code what I add self.desc.pack() to show
this is output

How do I fix this strange exception : Exception in Tkinter callback

I am working on a YouTube downloader project that takes a link and then puts the information about the video quality and sound quality of the link in the Combobox.
But when I try to put audio and video information in the Combobox, it gives this exception:
This is my code :
import tkinter
import tkinter.ttk
from tkinter import *
from tkinter import filedialog
from os import path
import pafy
from pafy import *
class Youtube():
def __init__(self):
self.label()
self.entry()
self.button()
self.combobox()
self.data=[]
def label(self):
Label(window, text='URL', font='bold').grid(row=0, column=0, padx=100)
Label(window, text='Destination', font='bold').grid(row=2, column=0, padx=100)
Label(window, text='File Name', font='bold').grid(row=4, column=0, padx=100)
Label(window, text='Video Quality', font='bold').grid(row=6, column=0, pady=20)
Label(window, text='Audio Quality', font='bold').grid(row=7, column=0, pady=5)
Label(window, text='Download Type', font='bold').grid(row=8, column=0, pady=15)
Label(window, text='Combine AV', font='bold').grid(row=8, column=1)
def entry(self):
global een
global en
en=Entry(window, width=35, borderwidth=10)
en.grid(row=1, column=0, padx=100, pady=5)
een=Entry(window, width=35, borderwidth=10)
een.grid(row=3, column=0, padx=100, pady=5)
Entry(window, width=35, borderwidth=10).grid(row=5, column=0, padx=100, pady=5)
def button(self):
Button(window, text='i', height=1, width=3, command=self.information).grid(row=1, column=1)
Button(window, text='d', height=1, width=3, command=self.destination).grid(row=3, column=1)
Button(window, text='Download', font='bold').grid(row=12, column=0, padx=150, pady=10, columnspan=3)
def combobox(self):
tkinter.ttk.Combobox(window, width=15).grid(row=6, column=1)
tkinter.ttk.Combobox(window, width=15).grid(row=7, column=1, pady=5)
tkinter.ttk.Combobox(window, values=['Audio only', 'Vido only', 'Audio and vido'],
width=15).grid(row=9, column=0)
tkinter.ttk.Combobox(window, values=['Yes', 'No'], width=15).grid(row=9, column=1, pady=20)
tkinter.ttk.Progressbar(window, orient=HORIZONTAL, length=300,
mode='determinate').grid(row=11, column=0, padx=200, pady=10, columnspan=3)
def destination(self):
path = str(filedialog.askdirectory())
een.insert(tkinter.END, path)
def information(self):
global link
link = en.get()
self.video()
self.audio()
def video(self):
video_quality_list = []
self.data = pafy.new(link)
video_streams = self.data.videostreams
for video_quality in video_streams:
video_quality_list.append(video_quality)
tkinter.ttk.Combobox(window, values=video_quality_list, width=15).grid(row=6, column=1, pady=5)
def audio(self):
audio_quality_list = []
self.data = pafy.new(link)
audio_streams = self.data.audiostreams
for audio_quality in audio_streams:
audio_quality_list.append(audio_quality)
tkinter.ttk.Combobox(window, values=audio_quality_list, width=15).grid(row=7, column=1)
window = Tk()
mywin = Youtube()
window.title('Youtube Downloader')
window.geometry("700x600+10+10")
window.mainloop()
I would be very grateful if anyone could help me to fix it.
Thanks!

tkinter clickable Label to open details of Label [duplicate]

This question already has answers here:
tkinter creating buttons in for loop passing command arguments
(3 answers)
Closed 6 months ago.
I'm trying to program an interface with tkinter, that shows users of my application as a list of Labels. The list is created from a database (created with sqlite3).
By clicking on each Label the program should open another window, showing details of the clicked user.
maybe do I need to use classes? (because for now, my script is not OOP)
root = Tk()
root.title("Utenti")
root.iconbitmap("D:\Willow\WilloW SW Gestionale")
root.geometry("365x600")
def open_user(name = str):
user = Tk()
user.title("Utenti")
user.iconbitmap("D:\Willow\WilloW SW Gestionale")
user.geometry("500x400")
#create entry
f_name_entry = Entry(user, width=30, state="disabled")
f_name_entry.grid(row=0, column=1, padx=20, pady=(10, 0))
P_iva_entry = Entry(user, width=30, state="disabled")
P_iva_entry.grid(row=1, column=1)
cell_number_entry = Entry(user, width=30, state="disabled")
cell_number_entry.grid(row=2, column=1)
tax_entry = Entry(user, width=30, state="disabled")
tax_entry.grid(row=3, column=1)
inps_entry = Entry(user, width=30, state="disabled")
inps_entry.grid(row=4, column=1)
# create text boxes
f_name_label = Label(user, text=name)
f_name_label.grid(row=0, column=0, pady=(10, 0))
P_iva_label = Label(user, text="p iva")
P_iva_label.grid(row=1, column=0)
cell_number_label = Label(user, text="cell number")
cell_number_label.grid(row=2, column=0)
tax_label = Label(user, text="tax")
tax_label.grid(row=3, column=0)
inps_label = Label(user, text="inps")
inps_label.grid(row=4, column=0)
i = 4
conn = sqlite3.connect("usersEsteso.db")
c = conn.cursor()
c.execute("SELECT *, oid FROM usersEsteso")
records = c.fetchall()
for record in records:
print_records = record[0]
users_lable = Label(root, bg="#778899")
users_lable.grid(row=i + 7, column=0, sticky="w", padx=5, pady=5, columnspan=3)
user_text = Label(users_lable, text=print_records)
user_text.grid(row=0, column=0, pady=5, padx=5, sticky="w")
#user_text.bind("<Enter>", open_user("sam"))
openUser_lable_button = Button(users_lable, text="apri " + record[0], command=lambda: open_user(record[0])) #here i showld pass the identification of the parent the button
openUser_lable_button.grid(row=1, column=0, pady=5, padx=5, sticky="e")
i = i + 1
conn.commit()
conn.close()
here the previous code, without database and simplyfied:
from tkinter import *
root = Tk()
root.title("Users")
root.geometry("365x600")
#global variables
i = 1
def open_user():
user = Tk()
user.title("User")
user.geometry("500x400")
#create entry
f_name_entry = Entry(user, width=150, state="normal")
f_name_entry.grid(row=0, column=1, padx=20, pady=(10, 0))
P_iva_entry = Entry(user, width=150, state="disabled")
P_iva_entry.grid(row=1, column=1, columnspan=2)
cell_number_entry = Entry(user, width=150, state="disabled")
cell_number_entry.grid(row=2, column=1, columnspan=2)
tax_entry = Entry(user, width=150, state="disabled")
tax_entry.grid(row=3, column=1, columnspan=2)
inps_entry = Entry(user, width=150, state="disabled")
inps_entry.grid(row=4, column=1, columnspan=2)
# create text boxes
f_name_label = Label(user, text="name")
f_name_label.grid(row=0, column=0, pady=(10, 0))
P_iva_label = Label(user, text="p iva")
P_iva_label.grid(row=1, column=0)
cell_number_label = Label(user, text="cell number")
cell_number_label.grid(row=2, column=0)
tax_label = Label(user, text="tax")
tax_label.grid(row=3, column=0)
inps_label = Label(user, text="inps")
inps_label.grid(row=4, column=0)
f_name_entry.insert(0, "here should be the name of the clicked user")
my_list = ["andrew", "sam", "Zoe"]
title_label = Label(root, text="List of Users")
title_label.grid(row=0, column=0, pady=(10,40))
for item in my_list:
print(i)
my_frame = Frame(root, bg="#a6a6a6")
my_label = Label(my_frame, text=item)
my_button = Button(my_frame, text="inspect user", command=open_user)
my_frame.grid(row=i, column=0, padx=10, pady=10)
my_label.grid(row=0, column=0, padx=10, pady=10)
my_button.grid(row=1, column=0, padx=10, pady=10)
i = i+1
root.mainloop()

Categories