Tkinter: How do I clear the window? - python-3.x

So this program asks for a name and last name. I'm looking for the program to clear and show "Welcome " + name + " " + lastname.
import sys
from tkinter import *
def salir():
sys.exit()
root = Tk()
root.wm_title('Matricula UTEC')
Label(root, text = "Bienvenido a Matricula UTEC").grid(row = 0)
Label(root, text = "Ingrese sus nombres: ").grid(row = 1)
Label(root, text = "Ingrese sus apellidos: ").grid(row = 2)
e1 = Entry(root)
e2 = Entry(root)
e1.grid(row=1, column = 1)
e2.grid(row=2, column = 1)
Button(root, text = 'Salir', command = salir).grid(row = 4, column = 0, sticky = W, pady = 4)
Button(root, text = 'Comenzar', command = salir).grid(row = 4, column = 1, sticky = W, pady = 4)
root.mainloop()

The simplest solution is to put everything you want to "clear" in a frame. Then, you can simply delete the frame and replace it with a different frame.
Here's a really simple example:
import sys
from tkinter import *
def salir():
login_frame.destroy()
home_frame = home()
home_frame.pack(fill="both", expand=True)
def login():
frame = Frame(root)
Label(frame, text = "Bienvenido a Matricula UTEC").grid(row = 0)
Label(frame, text = "Ingrese sus nombres: ").grid(row = 1)
Label(frame, text = "Ingrese sus apellidos: ").grid(row = 2)
e1 = Entry(frame)
e2 = Entry(frame)
e1.grid(row=1, column = 1)
e2.grid(row=2, column = 1)
Button(frame, text = 'Salir', command = salir).grid(row = 4, column = 0, sticky = W, pady = 4)
Button(frame, text = 'Comenzar', command = salir).grid(row = 4, column = 1, sticky = W, pady = 4)
return frame
def home():
frame = Frame(root)
Label(frame, text="Welcome").pack()
return frame
root = Tk()
root.wm_title('Matricula UTEC')
login_frame = login()
login_frame.pack(fill="both", expand=True)
root.mainloop()

Related

How can I scroll multiple frames in canvas?

I want to create a list of frames with further features like a button, label e.g.. but my issues are the size of the LabelFrame. If I put the LabelFrame in container it fits like I want to but it isn't scrollable any more. Any ideas?
from tkinter import ttk
import tkinter as tk
root = tk.Tk()
container = ttk.Frame(root)
canvas = tk.Canvas(container)
scrollbar = ttk.Scrollbar(container, orient="vertical", command=canvas.yview)
scrollable_frame = ttk.Frame(canvas)
scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(
scrollregion=canvas.bbox("all")
)
)
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
for i in range(50):
lf = ttk.Frame(scrollable_frame, text=i).grid(column=1, row=i)
frame_ip = tk.LabelFrame(lf, bg="white", text=i)
frame_ip.place(relwidth=0.95, relheight=0.2, relx=0.025, rely=0)
button_scroll1 = tk.Button(frame_ip, text="Start", bg="grey")
button_scroll1.place(relwidth=0.15, relx=0.025, relheight=0.15, rely=0.1)
container.pack()
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
root.mainloop()
Here is your updated code with a Button, Canvas and Scrollbar inserted into each LabelFrame with grid manager.
I've also made the container resizable with row|column configure.
Seems to work fine.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.rowconfigure(0, weight = 1)
root.columnconfigure(0, weight = 1)
root.geometry("341x448")
container = ttk.Frame(root)
container.rowconfigure(0, weight = 1)
container.columnconfigure(0, weight = 1)
canvas = tk.Canvas(container)
scrollbar = ttk.Scrollbar(container, orient = tk.VERTICAL, command = canvas.yview)
scrollable_frame = ttk.Frame(canvas)
scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(
scrollregion=canvas.bbox("all")))
canvas.create_window((0, 0), window = scrollable_frame, anchor = tk.NW)
canvas.configure(yscrollcommand = scrollbar.set)
for i in range(15):
L = ttk.LabelFrame(scrollable_frame, text = "Sample scrolling label")
L.grid(row = i, column = 0, sticky = tk.NSEW)
B = ttk.Button( L, text = f"Button {i}")
B.grid(row = 0, column = 0, sticky = tk.NW)
K = tk.Canvas(
L, width = 300, height = 100,
scrollregion = "0 0 400 400", background = "#ffffff")
K.grid(row = 1, column = 0, sticky = tk.NSEW)
S = ttk.Scrollbar( L, command = K.yview)
S.grid(column = 1, row = 1, sticky = tk.NSEW)
K["yscrollcommand"] = S.set
container.grid(row = 0, column = 0, sticky = tk.NSEW)
canvas.grid(row = 0, column = 0, sticky = tk.NSEW)
scrollbar.grid(row = 0, column = 1, sticky = tk.NS)
root.mainloop()

How to get Get value of check button in python tkinter library?

I've created a travel form in which a user will submit name, city, gender, phone number etc. Also, I've created a check button so that a user wants a meal he can tick on the check button.
My Question is How to get values of the Check button if the user has ticked the meal query written in the code.
Can anyone explain to me the logic on how to get the value of the Check button if the user has ticked on it?
from tkinter import *
root = Tk()
root.geometry('800x800')
def b():
print('Name is', namevalue.get()),
print('Phone number is', phonevalue.get())
print('Gender is', gendervalue.get()),
print('Extra Phone number is', phone1value.get()),
print('City is', cityvalue.get())
print('Food is required', )
f1 = Frame(root, bg = 'red', borderwidth = 8, relief = SUNKEN)
f1.grid()
Label(f1, text = 'Welcome to travel agency', pady = 5).grid(row = 0, column = 3)
#Making Widgets or we may call headers
name = Label(root, text = 'name')
phone = Label(root, text = 'Phone')
gender = Label(root, text = 'Enter your gender')
phone1 = Label(root, text = 'Extra Number')
city = Label(root, text = 'Your City')
name.grid(row = 1,column = 0)
phone.grid(row = 2,column = 0)
gender.grid(row = 3, column = 0)
phone1.grid(row = 4, column = 0)
city.grid(row = 5, column = 0)
#Assigining the headers a variable type
namevalue = StringVar()
phonevalue = StringVar()
gendervalue = StringVar()
phone1value = StringVar()
cityvalue = StringVar()
foodservicevalue = IntVar()
nameentry = Entry(root, textvariable = namevalue)
phoneentry = Entry(root, textvariable = phonevalue)
genderentry = Entry(root, textvariable = gendervalue)
cityentry = Entry(root, textvariable = cityvalue)
phone1entry = Entry(root, textvariable = phone1value)
nameentry.grid(row = 1, column = 3)
phoneentry.grid(row = 2, column = 3)
genderentry.grid(row = 3, column = 3)
phone1entry.grid(row = 4, column = 3)
cityentry.grid(row = 5, column = 3)
#Creating Check Button checkbutton
foodservicevalue = Checkbutton(text ='Do you wan\'t any meals', variable = foodservicevalue)
foodservicevalue.grid(row = 6, column = 3, padx = 1)
#Button and packing with assiginn
Button(text = 'Submit', command = b).grid(row = 7, column = 3)
root.mainloop()
This code works:
from tkinter import *
root = Tk()
root.geometry('800x800')
def b():
print('Name is', namevalue.get()),
print('Phone number is', phonevalue.get())
print('Gender is', gendervalue.get()),
print('Extra Phone number is', phone1value.get()),
print('City is', cityvalue.get())
if food_required.get() == 1:
print("Food is required.")
elif food_required.get() == 0:
print("Food is not required.")
# When the check button is clicked, then the value is 1 and it can be get using the .get() function.
# Similarly when the check button is not clicked then the value is 0.
f1 = Frame(root, bg='red', borderwidth=8, relief=SUNKEN)
f1.grid()
Label(f1, text='Welcome to travel agency', pady=5).grid(row=0, column=3)
# Making Widgets or we may call headers
name = Label(root, text='name')
phone = Label(root, text='Phone')
gender = Label(root, text='Enter your gender')
phone1 = Label(root, text='Extra Number')
city = Label(root, text='Your City')
name.grid(row=1, column=0)
phone.grid(row=2, column=0)
gender.grid(row=3, column=0)
phone1.grid(row=4, column=0)
city.grid(row=5, column=0)
# Assigining the headers a variable type
namevalue = StringVar()
phonevalue = StringVar()
gendervalue = StringVar()
phone1value = StringVar()
cityvalue = StringVar()
food_required = IntVar()
nameentry = Entry(root, textvariable=namevalue)
phoneentry = Entry(root, textvariable=phonevalue)
genderentry = Entry(root, textvariable=gendervalue)
cityentry = Entry(root, textvariable=cityvalue)
phone1entry = Entry(root, textvariable=phone1value)
nameentry.grid(row=1, column=3)
phoneentry.grid(row=2, column=3)
genderentry.grid(row=3, column=3)
phone1entry.grid(row=4, column=3)
cityentry.grid(row=5, column=3)
# Creating Check Button #cHECKBUTTON
foodservicevalue = Checkbutton(text='Do you wan\'t any meals', variable=food_required)
foodservicevalue.grid(row=6, column=3, padx=1)
# Button and packing with assiginn
Button(text='Submit', command=b).grid(row=7, column=3)
root.mainloop()
When I saw your code, I found that you have used the variable foodservicevalue as an IntVar() and Checkbutton. I have used the if else statements to fix your issue.
This is #AmeyVijeesh's code but I removed the StringVars:
from tkinter import *
def b():
print("Name is", nameentry.get()),
print("Phone number is", phoneentry.get())
print("Gender is", genderentry.get()),
print("Extra Phone number is", phone1entry.get()),
print("City is", cityentry.get())
if food_required.get() == 1:
print("Food is required.")
elif food_required.get() == 0:
print("Food is not required.")
root = Tk()
root.geometry("800x800")
f1 = Frame(root, bg="red", borderwidth=8, relief="sunken")
f1.grid()
label = Label(f1, text="Welcome to travel agency", pady=5)
label.grid(row=0, column=3)
# Making Widgets or we may call headers
name = Label(root, text="Name")
phone = Label(root, text="Phone")
gender = Label(root, text="Enter your gender")
phone1 = Label(root, text="Extra Number")
city = Label(root, text="Your City")
name.grid(row=1, column=0)
phone.grid(row=2, column=0)
gender.grid(row=3, column=0)
phone1.grid(row=4, column=0)
city.grid(row=5, column=0)
# Assigining the headers a variable type
food_required = IntVar()
nameentry = Entry(root)
phoneentry = Entry(root)
genderentry = Entry(root)
cityentry = Entry(root)
phone1entry = Entry(root)
nameentry.grid(row=1, column=3)
phoneentry.grid(row=2, column=3)
genderentry.grid(row=3, column=3)
phone1entry.grid(row=4, column=3)
cityentry.grid(row=5, column=3)
# Creating Check Button #cHECKBUTTON
foodservicevalue = Checkbutton(text="Do you want any meals", variable=food_required)
foodservicevalue.grid(row=6, column=3, padx=1)
# Button and packing with assiginn
button = Button(text="Submit", command=b)
button.grid(row=7, column=3)
root.mainloop()
Using <tkinter.Entry>.get() is much simpler than creating StringVars and assigning them to the <tkinter.Entry>s

How do I insert entries from a child window in MySQL with Python 3.6

I'm new to this site and to programming. Right now I'm facing a challenge: I have to insert the entries from a form into a MySQL table with Python 3.6.2. The window in question is dynamic, meaning that I can add or remove fields from it (obviously, the table in the database will not be modified accordingly).
What I really need is to capture some of the entries from the form (and omit repetitive ones like "Confirm password" and "Confirm email"), but also from Address 2 (which is optional).
Below I paste my code (some of it adapted from this site). I omitted the SQL query because I don't know where I should place it. The data I need are those from "def create_window2()".
Thanks in advance.
import tkinter as tk
import MySQLdb
from tkinter import *
class MainWindow(tk.Frame):
counter = 0
def create_window2(self):
t = tk.Toplevel(self)
t.focus_force()
t.wm_title("New Customer Registration")
fields = ("Username*", "Password*", "Confirm password*", "First
Name*", "Last Name*", "Address 1*", "Address 2
(optional)", "Town/City", "Telephone Number*", "Email
address*", "Confirm email*")
def fetch(entries):
for entry in entries:
field = entry[0]
text = entry[1].get()
print('%s: "%s"' % (field, text))
def makeform(t, fields):
entries = []
for field in fields:
row = Frame(t)
label = Label(row, width = 20, text = field, anchor = 'w')
entry = Entry(row, width = 25)
row.pack(side = TOP, padx = 5, pady = 5)
label.pack(side = LEFT)
entry.pack(side = LEFT)
entries.append((field, entry))
return entries
if __name__ == '__main__':
root = t
root.geometry('+520+120')
ents = makeform(root, fields)
wm_button1 = Button(root, text = "Register", width = 15,
command = t.register)
wm_button1.pack(side = LEFT, padx = 35, pady = 5)
wm_button2 = Button(root, text = "Cancel", width = 15,
command = t.destroy)
wm_button2.pack(side = LEFT, padx = 10, pady = 5)
root.bind('<Return>', (lambda event, e = ents: fetch(e)))
root.mainloop()
This should get you started, although there is obviously more to do. This program uses instance objects/variables so you don't return values from functions as instance objects are usable anywhere in the class. Also, I am using grid() instead of pack() but that is just personal preference.
import tkinter as tk
##import MySQLdb
## from tkinter import * import tkinter once only
class MainWindow():
##counter = 0
def __init__(self, root):
self.t = tk.Toplevel(root)
self.t.geometry('+1000+10')
self.t.focus_force()
self.t.wm_title("New Customer Registration")
self.fields = ("Username*", "Password*", "Confirm password*",
"First Name*", "Last Name*", "Address 1*",
"Address 2 optional)", "Town/City", "Telephone Number*",
"Email address*", "Confirm email*")
self.entries=[]
self.makeform()
wm_button1 = tk.Button(root, text = "Register", width = 15,
command = self.fetch)
wm_button1.grid(row=1, column=0)
wm_button2 = tk.Button(root, text = "Cancel", width = 15,
command = self.t.destroy)
wm_button2.grid(row=2, column=0)
def fetch(self):
for entry in self.entries:
field = entry[0]
text = entry[1].get()
print('%s: "%s"' % (field, text))
##update to MariaDB would go here
self.input_frame.destroy()
self.makeform()
print("-"*50)
def makeform(self):
##use a Frame that will be destroyed
self.input_frame=tk.Frame(self.t)
self.input_frame.grid()
self.entries=[]
this_row=0
for field in self.fields:
label = tk.Label(self.t, width = 20, text = field, anchor = 'w')
entry = tk.Entry(self.t, width = 25)
label.grid(row=this_row, column=0, sticky="nsew")
entry.grid(row=this_row, column=1, sticky="nsew")
this_row += 1
self.entries.append((field, entry))
## change "fields" so it won't ask for Name & Password
self.fields = ("First Name*", "Last Name*", "Address 1*",
"Address 2 (optional)", "Town/City", "Telephone Number*",
"Email address*", "Confirm email*")
## not necessary, entires is an instance object
## return entries
if __name__ == '__main__':
root = tk.Tk()
root.geometry('+1000+300')
MW=MainWindow(root)
root.mainloop()
import tkinter as tk
import MySQLdb
from tkinter import *
class MainWindow(tk.Frame):
counter = 0
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
self.background = tk.PhotoImage(file = "D:\\UoB\\Herb\\water1.png")
self.back_label = tk.Label(self, image = self.background)
self.back_label.place(x = 0, y = 0, relwidth = 1, relheight = 1)
self.button1 = tk.Button(self, text = "Customer Login", width = 20, command=self.create_window1)
self.button1.place(relx = 0.5, rely = 0.20, anchor = CENTER)
self.button2 = tk.Button(self, text = "New Customer", width = 20, command=self.create_window2)
self.button2.place(relx = 0.5, rely = 0.40, anchor = CENTER)
self.button3 = tk.Button(self, text = "Driver", width = 20,command = self.create_window3)
self.button3.place(relx = 0.5, rely = 0.60, anchor = CENTER)
self.button4 = tk.Button(self, text = "Administrator", width = 20, command=self.create_window4)
self.button4.place(relx = 0.5, rely = 0.80, anchor = CENTER)
def create_window1(self):
t = tk.Toplevel(self)
t.focus_force()
t.wm_title("Customer Login")
t.geometry("380x180+535+275")
wm_labelText = StringVar()
wm_labelText.set("Username")
wm_labelUser = Label(t, textvariable = wm_labelText)
wm_labelUser.place(x = 20, y = 30)
username = StringVar(None)
user = Entry(t, textvariable = username, width = 30)
user.place(x = 100, y = 30)
wm_passwText = StringVar()
wm_passwText.set("Password")
wm_labelPass = Label(t, textvariable = wm_passwText)
wm_labelPass.place(x = 20, y = 65)
password = StringVar(None)
passw = Entry(t, textvariable = password, width = 30, show = "*")
passw.place(x = 100, y = 65)
wm_button1 = tk.Button(t, text = "Login", width = 15)
wm_button1.place(x = 30, y = 115)
wm_button2 = tk.Button(t, text = "Cancel", width = 15, command = t.destroy)
wm_button2.place(x = 210, y = 115)
def create_window2(self):
t = tk.Toplevel(self)
t.focus_force()
t.wm_title("New Customer Registration")
fields = ("Username*", "Password*", "Confirm password*", "First Name*", "Last Name*", "Address 1*", "Address 2", "Town/City", "Telephone Number*", "Email address*", "Confirm email*")
def fetch(entries):
for entry in entries:
field = entry[0]
text = entry[1].get()
print('%s: "%s"' % (field, text))
def makeform(t, fields):
entries = []
for field in fields:
row = Frame(t)
label = Label(row, width = 20, text = field, anchor = 'w')
entry = Entry(row, width = 25)
row.pack(side = TOP, padx = 5, pady = 5)
label.pack(side = LEFT)
entry.pack(side = LEFT)
entries.append((field, entry))
return entries
if __name__ == '__main__':
root = t
root.geometry('+520+120')
ents = makeform(root, fields)
label_new = Label(root, text = "All fields marked with * are mandatory")
label_new.config(font = ('times', 10, 'bold'))
label_new.pack()
wm_button1 = Button(root, text = "Register", width = 15, command = t.register)
wm_button1.pack(side = LEFT, padx = 35, pady = 5)
wm_button2 = Button(root, text = "Cancel", width = 15, command = t.destroy)
wm_button2.pack(side = LEFT, padx = 10, pady = 5)
root.bind('<Return>', (lambda event, e = ents: fetch(e)))
root.mainloop()
def create_window3(self):
t = tk.Toplevel(self)
t.focus_force()
t.wm_title("Driver Login")
t.geometry("380x180+535+275")
wm_labelText = StringVar()
wm_labelText.set("Username")
wm_labelUser = Label(t, textvariable = wm_labelText)
wm_labelUser.place(x = 20, y = 30)
username = StringVar(None)
user = Entry(t, textvariable = username, width = 30)
user.place(x = 100, y = 30)
wm_passwText = StringVar()
wm_passwText.set("Password")
wm_labelPass = Label(t, textvariable = wm_passwText)
wm_labelPass.place(x = 20, y = 65)
password = StringVar(None)
passw = Entry(t, textvariable = password, width = 30, show = "*")
passw.place(x = 100, y = 65)
wm_button1 = tk.Button(t, text = "Login", width = 15)
wm_button1.place(x = 35, y = 115)
wm_button2 = tk.Button(t, text = "Cancel", width = 15, command = t.destroy)
wm_button2.place(x = 215, y = 115)
def create_window4(self):
t = tk.Toplevel(self)
t.focus_force()
t.wm_title("Administrator Login")
t.geometry("380x180+535+275")
wm_labelText = StringVar()
wm_labelText.set("Username")
wm_labelUser = Label(t, textvariable = wm_labelText)
wm_labelUser.place(x = 20, y = 30)
username = StringVar(None)
user = Entry(t, textvariable = username, width = 30)
user.place(x = 100, y = 30)
wm_passwText = StringVar()
wm_passwText.set("Password")
wm_labelPass = Label(t, textvariable = wm_passwText)
wm_labelPass.place(x = 20, y = 65)
password = StringVar(None)
passw = Entry(t, textvariable = password, width = 30, show = "*")
passw.place(x = 100, y = 65)
wm_button1 = tk.Button(t, text = "Login", width = 15)
wm_button1.place(x = 30, y = 115)
wm_button2 = tk.Button(t, text = "Cancel", width = 15, command = t.destroy)
wm_button2.place(x = 210, y = 115)
if __name__ == "__main__":
root = tk.Tk()
main = MainWindow(root)
root.iconphoto( root, PhotoImage( file="D:\\UoB\\Herb\\bubbles.png" ) )
root.title( "Welcome to Sky Laundry" )
root.geometry( "400x400+525+175" )
main_menu = Menu( root, tearoff=0 )
main_menu.add_command( label="Quit", command = root.destroy )
root.config( menu = main_menu )
main.pack(side = "top", fill = "both", expand = True)
root.mainloop()

Python 3 tkinter insert file contents into a text box

Okay so I have done about 10 days of searching and I caved in so I'm turning to the community for help.
I am using python 3.6 and tkinter as a user interface.
The basic's of what I'm trying to accomplish is that I have a file that I open and search for a word within the file and insert all the lines that word falls on.
My issue is that its only inserting the first line it finds and I need it to insert all the lines it finds. Sorry for wet coding I'll dry it up once I have functionality later
here's a sample of my code (it's not the full thing but it should give you more than enough info about what I'm trying to accomplish):
import tkinter as tk
from tkinter import ttk
# i added all my imports that this class use's in case you guys think they could pose a problem but they shouldn't be a issue
class EXAMPLEapp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.iconbitmap(self, default = "dlm64.ico")
tk.Tk.wm_title(self, "Example.")
self.FILE_MENU_BAR()
self.minsize(width = 360, height = 200)
container = tk.Frame(self)
container.grid(row=0,column=0, sticky="nsew")
container.grid_rowconfigure(0, weight = 1)
container.grid_columnconfigure(0, weight = 1)
self.frames = {}
for FRAME in (SearchPage):
frame = FRAME(container, self)
self.frames[FRAME] = frame
frame.grid(row = 0, column = 0, sticky = "nsew")
self.show_frame(SearchPage)
def FILE_MENU_BAR(self):
#File
self.menubar = tk.Menu()
self.configure(menu = self.menubar)
File_Menu = tk.Menu(self.menubar, tearoff = False)
self.menubar.add_cascade(label = "File", menu = File_Menu)
File_Menu.add_command(label = "EXIT" , command = self.File_EXIT)
# Edit Menu
Edit_Menu = tk.Menu(self.menubar, tearoff = False)
self.menubar.add_cascade(label = "Edit", menu = Edit_Menu)
Edit_Menu.add_command(label = "cut", underline = 2, command = self.Edit_Cut)
Edit_Menu.add_command(label = "copy", underline = 0, command = self.Edit_Copy)
def File_EXIT(self):
sys.exit(0)
def Edit_Cut(self):
print("CUT")
def Edit_Copy(self):
print("COPY")
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class SearchPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text = "Search Inventory", font = ("Helvetica", 20, 'bold', 'underline'))
label.grid(row = 0, column = 1, sticky = "nsew", pady = (0,0), padx = (0,0))
button0 = ttk.Button(self, text = "Inventory Search")
button0.grid(row = 0, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
button1 = ttk.Button(self, text = "New Inventory", command = lambda: controller.show_frame(CreatePage))
button1.grid(row = 1, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
button2 = ttk.Button(self, text = "Edit Invetory", command = lambda: controller.show_frame(EditPage))
button2.grid(row = 2, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
button3 = ttk.Button(self, text = "Ship", command = lambda: controller.show_frame(ShipPage))
button3.grid(row = 3, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
button4 = ttk.Button(self, text = "Graph", command = lambda: controller.show_frame(PlotPage))
button4.grid(row = 4, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
DATE_VAR = tk.StringVar()
def DATE_SEARCH():
USER_TEXT = DATE_VAR.get()
with open('SAMPLE.txt', 'r') as searchfile:
for line in searchfile:
if USER_TEXT == '':
LABEL = tk.Text(self, width = 30, height = 2, wrap = tk.WORD, foreground = 'red')
LABEL.grid(row = 6, column = 3, sticky = "nsew", pady = (0,0), padx = (20,0))
LABEL.insert(1.0, "PLEASE ENTER A VALUE")
LABEL.configure(state = 'disabled')
break
elif USER_TEXT in line:
LABEL = tk.Text(self, width = 100, height = 4, wrap = tk.WORD)
LABEL.grid(row = 6, column = 3, sticky = "e", pady = (0,0), padx = (20,0))
LABEL.insert(1.0, line)
LABEL.configure(state = 'disabled')
ScrollBar = tk.Scrollbar(self)
ScrollBar.config(command = LABEL.yview)
LABEL.config(yscrollcommand = ScrollBar.set)
ScrollBar.grid(row = 6, column = 4, sticky = "e")
break
else:
LABEL = tk.Text(self, width = 30, height = 2, wrap = tk.WORD, foreground = 'red')
LABEL.grid(row = 6, column = 3, sticky = "nsew", pady = (0,0), padx = (20,0))
LABEL.insert(1.0, "INVENTORY DOES NOT EXIST")
LABEL.configure(state = 'disabled')
DATE_Search_label = tk.Label(self, text = "Search by DATE", font = ("Helvetica", 9))
DATE_Search_label.grid(row = 5, column = 1, sticky = "nsew")
DATE_Search_Entry = tk.Entry(self, textvariable = DATE_VAR)
DATE_Search_Entry.grid(row = 6, column = 1, sticky = "nsew", pady = 0, padx = 2)
DATE_SEARCH_BUTTON = ttk.Button(self, text = "Search", command = DATE_SEARCH)
DATE_SEARCH_BUTTON.grid(row = 6, column = 2, sticky = "nsew")
app = EXAMPLEapp()
app.mainloop()
EDIT:
I have made several changes to your code.
There were way too many emblems with the way you had it set up.
As I am not 100% sure how what you are trying to accomplish I have made progress with your code.
Below is the edited version of your code.
I also created a text file on my end to test with and it seams to have worked so let me know if this is getting close to what you are attempting to do.
A few notes:
1st I moved everything into one class. The way you had it set up was just not going to work without some major changes.
2nd I needed to add self. to many of your variables because they are variables that we need to interact with in the class.
3rd I changed they way you get the data from the entry box. The way you were doing it was just not working so I simplified it by adding .get() function to the entry variable.
4th but probably should have been the 1st thing I mentions. The way you had your main Tk() window starting was odd. I changed how root was created and how we pass it into the class. This seams to make more sense to me.
This is much better to use IMO.
Let me know what parts you still need explanation on and I will make updates to my answer as needed.
Update:
change the while open statement a bit. You do not need to recreate the text box and reconfigure it ever for loop this is not good and will prevent you from seeing multiple items. Also I do not believe you can have a multi line label thought I have never tried. Lets change this to a text box this should do what we need.
import tkinter as tk
from tkinter import ttk
class EXAMPLEapp(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.root = parent
self.root.wm_title("TM Duch\'e Nut CO.")
self.FILE_MENU_BAR()
self.root.minsize(width = 360, height = 200)
self.container = tk.Frame(self.root)
self.container.grid(row=0,column=0, sticky="nsew")
self.container.grid_rowconfigure(0, weight = 1)
self.container.grid_rowconfigure(6, weight = 0)
self.container.grid_columnconfigure(0, weight = 1)
self.container.grid_columnconfigure(3, weight = 0)
self.label = tk.Label(self.root, text = "Search Inventory", font = ("Helvetica", 20, 'bold', 'underline'))
self.label.grid(row = 0, column = 1, sticky = "nsew", pady = (0,0), padx = (0,0))
self.button0 = ttk.Button(self.root, text = "Inventory Search")
self.button0.grid(row = 0, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
self.button1 = ttk.Button(self.root, text = "New Inventory", command = lambda: controller.show_frame(CreatePage))
self.button1.grid(row = 1, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
self.button2 = ttk.Button(self.root, text = "Edit Invetory", command = lambda: controller.show_frame(EditPage))
self.button2.grid(row = 2, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
self.button3 = ttk.Button(self.root, text = "Ship", command = lambda: controller.show_frame(ShipPage))
self.button3.grid(row = 3, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
self.button4 = ttk.Button(self.root, text = "Graph", command = lambda: controller.show_frame(PlotPage))
self.button4.grid(row = 4, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
self.DATE_Search_label = tk.Label(self.root, text = "Search by DATE", font = ("Helvetica", 9))
self.DATE_Search_label.grid(row = 5, column = 1, sticky = "nsew")
self.DATE_Search_Entry = tk.Entry(self.root)
self.DATE_Search_Entry.grid(row = 6, column = 1, sticky = "nsew", pady = 0, padx = 2)
self.DATE_SEARCH_BUTTON = ttk.Button(self.root, text = "Search", command = lambda: self.DATE_SEARCH())
self.DATE_SEARCH_BUTTON.grid(row = 6, column = 2, sticky = "nsew")
def DATE_SEARCH(self):
with open('SAMPLE.txt', 'r') as f:
search_f = f.readlines()
self.text = tk.Text(self.root, width = 30, height = 2)
self.text.grid(row = 6, column = 3, sticky = "ew", pady = (0,0), padx = (20,0))
self.ScrollBar = tk.Scrollbar(self.root)
self.ScrollBar.config(command = self.text.yview)
self.text.config(yscrollcommand = self.ScrollBar.set)
self.ScrollBar.grid(row = 6, column = 4, sticky = "ns")
self.text.delete(1.0, "end-1c")
USER_TEXT = self.DATE_Search_Entry.get()
if USER_TEXT == '':
self.text.config(foreground = 'red')
self.text.insert(tk.END, "PLEASE ENTER A VALUE")
else:
match_in_file = False
for line in search_f:
if USER_TEXT in line:
self.text.config(foreground = 'black')
self.text.insert(tk.END, "{}".format(line))
match_in_file = True
if match_in_file == False:
self.text.config(foreground = 'red')
self.text.insert(tk.END, "INVENTORY DOES NOT EXIST")
def FILE_MENU_BAR(self):
#File
self.menu = tk.Menu(self.root)
self.root.config(menu = self.menu)
self.fileMenu = tk.Menu(self.menu, tearoff = 0)
self.menu.add_cascade(label = "File", menu = self.fileMenu)
self.fileMenu.add_separator()
self.fileMenu.add_command(label = "Exit", command = lambda: self.root.destroy())
# Edit Menu
self.Edit_Menu = tk.Menu(self.menu)
self.menu.add_cascade(label = "Edit", menu = self.Edit_Menu)
self.Edit_Menu.add_command(label = "cut", underline = 2, command = self.Edit_Cut)
self.Edit_Menu.add_command(label = "copy", underline = 0, command = self.Edit_Copy)
def File_EXIT(self):
sys.exit(0)
def Edit_Cut(self):
print("CUT")
def Edit_Copy(self):
print("COPY")
root = tk.Tk()
app = EXAMPLEapp(root)
app.mainloop()

Multiple parallel actions in tkinter's button command

I would like to add parallel actions in one button in tkinter window, this is my main code
from Fonctions import *
from time import time, sleep
listConnextion = [a,b,c,d,e,f]
MotDePasse= ""
class ConnecOptimizerApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
tk.Tk.iconbitmap(self , default= "logo.ico")
tk.Tk.wm_title(self,"ConnecOptimizer")
container = tk.Frame(self)
container.pack(side = "top", fill = "both", expand = True)
self.frames ={}
for f in (PageAccueil, PageAttente):
frame = f(container,self)
self.frames[f] = frame
frame.grid(row = 1000, column = 500, sticky = "nsew")
self.show_frame(PageAccueil)
def show_frame(self,cont):
frame = self.frames[cont]
frame.tkraise()
class PageAccueil(tk.Frame):
def __init__(self,parent,controller):
def cocher():
if var4 == 0:
ip.configure(state='disabled')
else:
ip.configure(state='normal')
tk.Frame.__init__(self,parent)
Frame0 = ttk.Frame(self)
Frame0.pack(side="top")
Frame1 = ttk.Frame(Frame0)
Frame1.pack(side="left", padx=70, pady=50)
Frame2 = ttk.Frame(Frame0)
Frame2.pack(side="left", padx=10, pady=10)
Frame3 = ttk.Frame(self)
Frame3.pack(side="top")
Frame4 = ttk.Frame(Frame3)
Frame4.pack(side = "left")
Frame5 = ttk.Frame(Frame3)
Frame5.pack(side = "left")
Fr = ttk.Frame(self).pack(side = "top")
Frame6 = ttk.Frame(self)
Frame6.pack(side = "top")
Frame7 = ttk.Frame(Frame6)
Frame7.pack(side="left")
Frame8 = ttk.Frame(Frame6)
Frame8.pack(side="left")
Frame9 = ttk.Frame(self)
Fr2 = ttk.Frame(self).pack(side = "top")
Frame9.pack(side = "top")
Frame10 = ttk.Frame(Frame9)
Frame10.pack(side = "left")
Frame11 = ttk.Frame(Frame9)
Frame11.pack(side = "left")
Frame12 = ttk.Frame(self)
Frame12.pack(side = "top")
varGr = tk.StringVar()
varGr.set(0)
for i in range(len(listConnextion)):
b = ttk.Radiobutton(Frame1, variable=varGr, text=listConnextion[i], value=i)
b.grid(row=i , sticky = "w")
var1 = tk.IntVar()
ttk.Checkbutton(Frame2, text="Graphique", variable=var1).grid(row=1 ,sticky = "w" )
var2 = tk.IntVar()
ttk.Checkbutton(Frame2, text="Diagnostic", variable=var2).grid(row=2 , sticky = "w")
var3 = tk.IntVar()
ttk.Checkbutton(Frame2, text="Optimisation", variable=var3).grid(row=3 , sticky = "w")
lab = ttk.Label(Frame4, text = "Periode de reference de l'historique en jour ")
lab.pack(side = "left" , padx = 30 )
nbJour = ttk.Entry(Frame5)
nbJour.pack(side = "left" )
l = ttk.Label(Fr).pack()
lab2 = ttk.Label(Frame7, text = "Nombre d'entrées pour finir l'apprentissage")
lab2.pack(side = "left" , padx = 30)
nbEntre = ttk.Entry(Frame8)
nbEntre.pack(side = "left" )
l2 = ttk.Label(Fr2).pack()
var4 = tk.IntVar()
ttk.Checkbutton(Frame10 , text = "Iperf", variable = var4 , command = cocher).pack( padx = 10)
ip = ttk.Entry(Frame11 , state = 'disabled')
ip.pack(padx = 20)
B = ttk.Button(Frame12, text="Valider" , command = (lambda: controller.show_frame(PageAttente)))
B.pack(side = "top" , pady = 30)
class PageAttente(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
frame0 = ttk.Frame(self)
frame0.pack(side = "top")
frame1 = ttk.Frame(self)
frame1.pack(side = "top")
self.T = tk.Text(frame0, height=20, width=53)
self.S = ttk.Scrollbar(frame0)
self.T.config(yscrollcommand=self.S.set)
self.T.pack(side=tk.LEFT, fill=tk.Y)
self.S.config(command=self.T.yview)
self.S.pack(side=tk.RIGHT, fill=tk.Y)
self.updateWidgets()
ttk.Button(frame1, text = "Arreter Diagnostic", command = (lambda : controller.show_frame(PageAccueil)) ).pack(pady = 10)
def updateWidgets(self):
with open('text.txt') as f:
newText = f.read()
self.T.delete('1.0', tk.END)
self.T.insert(tk.END, newText)
self.after(1000, self.updateWidgets)
app = ConnecOptimizerApp()
app.geometry("450x400+300+140")
app.mainloop()
and here you can find my fonctions
import tkinter as tk
from tkinter import ttk
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
def PageLogin():
root = tk.Tk()
root.geometry("350x130+530+280")
root.title("Super-utilisateur")
def leave():
MotDePasse = champMp.get()
print(MotDePasse)
root.destroy()
topFrame = ttk.Frame(root)
topFrame.pack()
middleFrame = ttk.Frame(root)
middleFrame.pack()
bottomFrame = ttk.Frame(root)
bottomFrame.pack()
lab1 = ttk.Label(topFrame, text=" ").pack()
lab2 = ttk.Label(topFrame, text="Veuillez entrer le mot de passe super-utilisateur").pack()
labelMessage2 = ttk.Label(middleFrame, text="mot de passe ")
labelMessage2.pack(side="left", padx=10, pady=10)
champMp = ttk.Entry(middleFrame, show='*')
champMp.pack(side="right", padx=10, pady=10)
b = ttk.Button(bottomFrame, text="valider", command = leave)
b.grid(row=4, pady=5, sticky="w")
root.mainloop()
def TracerGraphe ():
style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
ax2 = fig.add_subplot(1, 1, 1)
ax3 = fig.add_subplot(1, 1, 1)
def animate(i):
graph_data = open('test.txt', 'r').read()
lines = graph_data.split('\n')
xs = []
ys = []
zs = []
ws = []
for line in lines:
if len(line) > 1:
x, y, z, w = line.split(',')
xs.append(x)
ys.append(y)
zs.append(z)
ws.append(w)
ax1.clear()
ax2.clear()
ax3.clear()
ax1.plot(xs, ys, label='RTT')
ax2.plot(xs, zs, label='Debit')
ax3.plot(xs, ws, label='taux d erreur')
ax1.legend()
ax2.legend()
ax3.legend()
ani = animation.FuncAnimation(fig, animate, interval=1000)
mngr = plt.get_current_fig_manager()
mngr.window.setGeometry(700, 100, 640, 545)
plt.show()
What I cant is : When I press the B button I want to show the PageAttente using "lambda: controller.show_frame(PageAttente)" , show the LoginPage using "PageLogin()" fonction and show the graph using "TracerGraphe ()"
I have tried all the solutions I found on net but it doesnt work
Can anyone help me please ?
Thanks

Resources