Unable to create elements within notebook tab python tkinter - python

I have 2 files where I want to put a list of images from my database into my tkinter notebook tab upon searching through my database. However I am unable to do so as when I execute the search button , my tab which the images and details should be populated into still it remains empty. In addition, the details are only shown when I closed the initial application in which a second application will then open to show the details. However what I want is for the details to be populated straightaway into my tkinter notebook tab. Can I ask for some guidance on how I should amend my code?
from cProfile import label
from tkinter import *
from PIL import ImageTk, Image
from tkinter import ttk
root = Tk()
root.geometry("1300x600")
my_tabs = ttk.Notebook(root)
my_tabs.pack()
# style = ttk.Style()
# style.layout("TNotebook.Tab", [])
def back():
my_tabs.select(0)
def back1():
my_tabs.select(1)
def back2():
my_tabs.select(2)
def whenClicked():
global entry
entry = enTree.get()
print(entry,type(entry))
my_tabs.select(1)
my_frame = Frame(my_tabs, width=1300, height=600)
my_frame2 = Frame(my_tabs, width=1300, height=600)
my_frame3 = Frame(my_tabs, width= 1300, height=600)
my_frame4 = Frame(my_tabs, width= 1300, height=600)
my_frame5 = Frame(my_tabs, width= 1300, height=600)
my_frame6 = Frame(my_tabs, width= 1300, height=600)
my_frame.pack(fill="both", expand=1)
my_frame2.pack(fill="both", expand=1)
my_frame3.pack(fill="both", expand=1)
my_frame4.pack(fill="both", expand=1)
my_frame5.pack(fill="both", expand=1)
my_frame6.pack(fill="both", expand=1)
my_tabs.add(my_frame, text="1st tab")
my_tabs.add(my_frame2, text="2nd tab")
my_tabs.add(my_frame3, text="3rd tab")
my_tabs.add(my_frame4, text="4th tab")
my_tabs.add(my_frame5, text="5th tab")
my_tabs.add(my_frame6, text="6th tab")
img = (Image.open("Iphone.jfif"))
resizedImage = img.resize((300, 300), Image.ANTIALIAS)
img2 = ImageTk.PhotoImage(resizedImage)
img3 = (Image.open("Rating.png"))
resizedImage2 = img3.resize((300, 60), Image.ANTIALIAS)
img4 = ImageTk.PhotoImage(resizedImage2)
img5 = (Image.open("Cheese.png"))
resizeImage3 = img5.resize((80,80), Image.ANTIALIAS)
CheesePic = ImageTk.PhotoImage(resizeImage3)
emptyLabel = Label(my_frame)
emptyLabel.pack(pady=80)
#App name/Label
labelOne = Label(my_frame, text = "Compario", font=("Algerian", 50))
labelOne.pack(padx=10,pady=10, anchor=CENTER)
#Search box
enTree = Entry(my_frame, width=60, font=30)
enTree.pack(padx=10,pady=10, ipady=7, anchor=CENTER)
#Search button
buttonOne = Button(my_frame, text = "Search", font=("Arial", 15), padx=25, pady=6, fg="white", bg="grey", command=whenClicked)
buttonOne.pack(padx=10,pady=10,anchor=CENTER)
backButton = Button(my_frame2, text = "Back", command = back)
backButton.place(relx=0.07, rely=0.1, anchor=CENTER)
root.mainloop()
Here is my second file
from tkinter import *
from PIL import ImageTk, Image
from io import BytesIO
import requests
import sqlite3
import GUI3
root = Tk()
root.geometry("1300x600")
#Database output result from site into GUI
Links = []
PName = []
Price = []
Rating = []
a = []
b = []
c = []
d= []
def fetch_db():
connection = sqlite3.connect("site.db")
cursor = connection.cursor()
cursor.execute("SELECT IMAGE FROM products WHERE TITLE LIKE ?", ("%" + GUI3.entry + "%",))
all_tables = cursor.fetchall()
for row in all_tables[:4]:
Links.append(row)
for lItems in Links:
for lItem in lItems:
continue
a.append(lItem)
cursor.execute("SELECT TITLE FROM products WHERE TITLE LIKE ?", ("%" + GUI3.entry + "%",))
all_tables2 = cursor.fetchall()
for row in all_tables2[:4]:
PName.append(row)
for pdItems in PName:
for pdItem in pdItems:
continue
b.append(pdItem)
cursor.execute("SELECT PRICE FROM products WHERE TITLE LIKE ?", ("%" + GUI3.entry + "%",))
all_tables3 = cursor.fetchall()
for row in all_tables3[:4]:
Price.append(row)
for pItems in Price:
for pItem in pItems:
continue
c.append(pItem)
cursor.execute("SELECT RATING FROM products WHERE TITLE LIKE ?", ("%" + GUI3.entry + "%",))
all_tables4 = cursor.fetchall()
for row in all_tables4[:4]:
Rating.append(row)
for rItems in Rating:
for rItem in rItems:
continue
d.append(rItem)
connection.close()
fetch_db()
for z in range(0, len(a)):
r = requests.get(str(a[z]))
phoneImage = Image.open(BytesIO(r.content)).resize((160, 160), Image.Resampling.LANCZOS)
photo = ImageTk.PhotoImage(phoneImage)
label = Label(image=photo)
label.image = photo
bigB = str(b[z])
bigC = str(c[z])
bigD = str(d[z])
labelImage = Label(GUI3.my_frame2, text ="Hello Educba Technology Institute")
labelText = Label(GUI3.my_frame2, width=22, text=bigB, bg="white").place(x=10+(z+1)*200, y=190)
labelPrice = Label(GUI3.my_frame2, width=20, text=bigC, bg="white").place(x=20+(z+1)*200, y=220)
labelRating = Label(GUI3.my_frame2, width=20, text=bigD+"/5", bg="white").place(x=20+(z+1)*200, y=250)
z += 1

Related

how to display blob as image in a table in tkinter python

I am trying to insert and retrieve image from MySQL database.I have inserted the image as BLOB (longblob). When I am able to display it using image.show() but I want the image to be displayed in a table.
I used treeview for this purpose. But my table shows only BLOB objects. It doesn't show any image.
This is my code.
from tkinter import *
from PIL import ImageTk,Image
from tkinter import filedialog
import mysql.connector
import io
from tkinter import ttk
root = Tk()
id = Entry(root, width=10, font=("Helvetica", 20), bd=3)
id.pack()
browse_button = Button(root,text ='Browse',command = lambda:open_file())
browse_button.pack()
display_button = Button(root,text ='display',command =lambda:display_file())
display_button.pack()
display_table_button = Button(root,text ='display Table',command =lambda:display_Table())
display_table_button.pack()
def display_Table():
query = "SELECT * FROM image_db"
person = mysql.connector.connect(host="localhost", user="root", password="", database="image")
cursor_variable = person.cursor()
cursor_variable.execute(query)
vertical_scrollbar = ttk.Scrollbar(root)
vertical_scrollbar.pack(side=RIGHT, fill=Y)
my_tree = ttk.Treeview(root, yscrollcommand= vertical_scrollbar.set)
my_tree.pack()
vertical_scrollbar.config(command= my_tree.yview)
style = ttk.Style(root)
style.theme_use("winnative")
style.configure(".", font=("Helvetica", 11))
style.configure("Treeview.Heading", font=("Helvetica", 11, "bold"))
my_tree['columns'] = ("id", "data")
my_tree.column("#0", width=0, stretch='NO')
my_tree.column("id", width=50, anchor='w')
my_tree.column("data", width=130, anchor='w')
my_tree.heading("#0", anchor='w', text='Label')
my_tree.heading("id", anchor='w', text="Id")
my_tree.heading("data", anchor='w', text="Image")
count = 0
for record in cursor_variable:
# print(record)
my_tree.insert(parent='', index='end', iid=count, text='Parent',
values=(record[0], record[1]))
count += 1
person.close()
def display_file():
id2 = id.get()
person = mysql.connector.connect(host="localhost", user="root", password="", database="image")
cursor_variable = person.cursor()
sql = "SELECT data FROM image_db WHERE id = '" + id2 + "'"
cursor_variable.execute(sql)
all_data = cursor_variable.fetchall()
image = all_data[0][0]
image = Image.open(io.BytesIO(image))
image.show()
person.commit()
person.close()
def open_file():
root.filename = filedialog.askopenfilename(initialdir="/Users/write/PycharmProjects/slider/img", title='Select a File',
filetypes=(('png files', '*.png'), ('jpeg files', '*.jpeg'),
('jpg files', '*.jpg')))
my_label = Label(root, text=root.filename).pack()
my_image = ImageTk.PhotoImage(Image.open(root.filename))
path = root.filename
id1 = id.get()
person = mysql.connector.connect(host="localhost", user="root", password="", database="image")
cursor_variable = person.cursor()
thedata = open(root.filename, 'rb').read()
sql = "INSERT INTO image_db (id,data) VALUES ('" + id1 + "',%s)"
cursor_variable.execute(sql, (thedata,))
person.commit()
person.close()
root.mainloop()
Any help is appreciated.
I have modified your display_Table():
set the rowheight of treeview to 50
set width of column "#0" to 100
resize the retrieved image to fit the treeview cell
def display_Table():
...
style = ttk.Style(root)
style.theme_use("winnative")
style.configure(".", font=("Helvetica", 11))
style.configure("Treeview.Heading", font=("Helvetica", 11, "bold"))
style.configure("Treeview", rowheight=50) # set row height
my_tree['columns'] = ("id",)
my_tree.column("#0", width=100, stretch='NO') # set width
my_tree.column("id", width=100, anchor='w')
my_tree.heading("#0", anchor='w', text='Image')
my_tree.heading("id", anchor='w', text="Id")
count = 0
my_tree.imglist = []
for record in cursor_variable:
img = Image.open(io.BytesIO(record[1]))
img.thumbnail((50,50)) # resize the image to desired size
img = ImageTk.PhotoImage(img)
my_tree.insert(parent="", index="end", iid=count,
image=img, values=(record[0],)) # use "image" option for the image
my_tree.imglist.append(img) # save the image reference
count += 1
Note that I have used a list to hold the image references to avoid garbage collection.
The output:

Sqlite3 Accessing a specific record from a database from a different class and putting it into a tkinter entrybox

The function of this code is that it displays the list of records in a database with one of the fields being a button. When this button is clicked it brings the user to a new frame which displays the account information for that record.
The record information is displayed in the Record class as dat[0] and dat[1] and I have had problems with initializing this in the second class, I do not know how I would get this information to appear on the second screen.
Thanks for any help.
from tkinter import *
import sqlite3
import AddAccount
import RemoveAccount
import LogOnLib
import LoginMenu
import TrainerAccounts
class Records(object):
def __init__(self, window):
self.window = window
window.state("zoomed")
self.window.title('Trainer Accounts')
window.update_idletasks()
h = self.window.winfo_height()
w = self.window.winfo_width()
Center_h = h/2
Center_w = w/2
self.FrameRecords = Frame(window, bg = "PaleTurquoise1")
self.FrameRecords.place(x = Center_w , y = Center_h, anchor = "center", width = 1024, height = 300)
self.btn_Back = Button(self.FrameRecords, text = "Back", bg = "PaleTurquoise1", font =("Arial", "16"), command = self.Back, width = 20)
self.btn_Back.grid(row = 1, column = 4, columnspan = 5)
self.connection = sqlite3.connect(r"E:\Program\Accounts.db")
self.cur = self.connection.cursor()
self.btn_TrainerID = Label(self.FrameRecords, text = "Trainer ID", bg = "PaleTurquoise1", font =("Arial", "16"), width = 20)
self.btn_TrainerID.grid(row = 0, column = 1, columnspan = 1)
self.NameLabel = Label(self.FrameRecords, text = "Name", bg = "PaleTurquoise1", font =("Arial", "16"), width = 20)
self.NameLabel.grid(row=0, column=0)
self.showallrecords()
def showallrecords(self):
Data = self.readfromdatabase()
for index, dat in enumerate(Data):
self.row1 = Button(self.FrameRecords, text=dat[0],font =("Arial", "16"), command = self.account).grid(row=index+1, column=0)
self.row2 = Label(self.FrameRecords, text=dat[1],font =("Arial", "16")).grid(row=index+1, column=1)
def readfromdatabase(self):
self.cur.execute("SELECT * FROM Trainers")
return self.cur.fetchall()
self.btn_TrainerID = self.row1
self.NameLabel = self.row2
def Back(self):
self.FrameRecords.place_forget()
GUI = LoginMenu.Logged(self.window)
def account(self):
self.FrameRecords.place_forget()
GUI = TrainerAccounts.TrainerInfo(self.window, Records)
##########################################################################################################################################################################################
class TrainerInfo(Records):
def __init__(self, window, Records):
self.window = window
window.state("zoomed")
self.window.title('CHANGEEEE')
window.update_idletasks()
h = self.window.winfo_height()
w = self.window.winfo_width()
Center_h = h/2
Center_w = w/2
self.FrameTrainerInfo = Frame(window, bg = "PaleTurquoise1")
self.FrameTrainerInfo.place(x = Center_w , y = Center_h, anchor = "center", width = 1024, height = 300)
self.connection = sqlite3.connect(r"E:\Program\Accounts.db")
self.cur = self.connection.cursor()
self.showrecord()
def showrecord(self):
Data = self.Information()
for index, dat in enumerate(Data):
Label(self.FrameTrainerInfo, text=self.row1,font =("Arial", "16")).grid(row=index+1, column=0)
Label(self.FrameTrainerInfo, text=self.row2,font =("Arial", "16")).grid(row=index+1, column=1)
def Information(self):
self.cur.execute("SELECT * FROM Trainers WHERE row1 = '" + row1 + "'" + "AND row2 = '" + row2 + "'")
return self.cur.self.all()
Have you tried merging the two classes together ?
if you can push values from database you only need make a .insert on Entrybox
maybe like this
tkEntry = Entry( master)
tkEntry.pack() # .grid or .place, don't make this in obj create
tkEntry.insert( 0, dat[0] ) # 0 is the index and dat[0] is your value

Opening images from 2 folders and displaying them simultaneously in python

I would like to open images from 2 different folders and display them next to each other , also have a button " Next" to be able to move to the next pair of images.
The images paths are stored in a txt file , so lets say open the first image and the second image and when I click next , 3rd and 4th image and so on
I am new to python and this is what I found so far to read an image
from Tkinter import *
from PIL import ImageTk, Image
import os
root = Tk()
img = ImageTk.PhotoImage(Image.open("path.ppm"))
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()
But i can't figure how to open 2 images simultaneously and add the next button
Here is a working example of what you ask:
from tkinter import *
def UpdateImg ( ):
global img1, img2
img1 = PhotoImage(file=ImgFiles[Cur])
img2 = PhotoImage(file=ImgFiles[Cur+1])
LblImg1.configure(image = img1, text=ImgFiles[Cur])
LblImg2.configure(image = img2, text=ImgFiles[Cur+1] )
def BtnNext( ):
global Cur
if Cur < len(ImgFiles)-2:
Cur = Cur + 2
UpdateImg ( )
def BtnPrev( ):
global Cur
if Cur > 1:
Cur = Cur - 2
UpdateImg ( )
fp = open("ImgFilesSrc.txt", "r")
ImgFiles = fp.read().split('\n')
fp.close()
Cur = 0
img1 = img2 = ''
root = Tk()
#Create the main Frame -----------------------------------------------------------------
FrmMain = Frame(root)
LblImg1 = Label(FrmMain, text = "Picture 1", anchor=W, width=120, bg="light sky blue")
LblImg2 = Label(FrmMain, text = "Picture 2", anchor=W, width=120, bg="light sky blue")
BtnPrev = Button(FrmMain, text=" < ", width=10, command=BtnPrev)
BtnNext = Button(FrmMain, text=" > ", width=10, command=BtnNext)
LblImg1.grid (row=2, rowspan = 3, column=1, columnspan=3);
LblImg2.grid (row=2, rowspan = 3, column=4, columnspan=3);
BtnPrev.grid (row=5, column=2); BtnNext.grid(row=5, column=4)
FrmMain.pack(side=TOP, fill=X)
#--------------------------------------------------------------------------
UpdateImg ( )
root.mainloop()

python error run from cmd

For my coursework i am doing a booking system which uses some tree views. The problem is that if ran from cmd when i double click on a row in the tree view it does not populate the boxes below it, however if i run it from the idle it does. Below is my where i have made my class and two defs which are create_GUI(for first part of gui before double click) and double click(makes second part of GUI)
from tkinter import *
import os
import datetime
import sqlite3
from tkinter.ttk import Combobox,Treeview,Scrollbar
import tkinter as tk
import Utilities
class Application(Frame):
""" Binary to Decimal """
def __init__(self, master):
""" Initialize the frame. """
super(Application, self).__init__(master)
self.grid()
self.create_GUI()
def Quit(self):
self.master.destroy()
def create_GUI(self):
frame1 = tk.LabelFrame(root, text="frame1", width=300, height=130, bd=5)
frame2 = tk.LabelFrame(root, text="frame2", width=300, height=130, bd=5)
frame1.grid(row=0, column=0, columnspan=3, padx=8)
frame2.grid(row=1, column=0, columnspan=3, padx=8)
self.title_lbl = Label(frame1, text = "Students")
self.title_lbl.grid(row = 0, column = 2)
self.fn_lbl = Label(frame1, text = "First Name:")
self.fn_lbl.grid(row = 1 , column = 1)
self.fn_txt = Entry(frame1)
self.fn_txt.grid(row = 1, column = 2)
self.ln_lbl =Label(frame1, text = "Last Name:")
self.ln_lbl.grid(row = 2, column = 1)
self.ln_txt = Entry(frame1)
self.ln_txt.grid(row = 2, column = 2)
self.q_btn = Button(frame1, text = "Back",padx=80,pady=10, command = lambda: self.Quit())
self.q_btn.grid(row = 3, column = 0)
self.s_btn = Button(frame1, text = "search",padx=80,pady=10, command = lambda: self.search())
self.s_btn.grid(row = 3,column = 3)
self.tree = Treeview(frame2,height = 6)
self.tree["columns"] = ("StudentID","First Name","Last Name")#,"House Number", "Street Name", "Town Or City Name","PostCode","MobilePhoneNumber")
self.tree.column("StudentID",width = 100)
self.tree.column("First Name",width = 100)
self.tree.column("Last Name", width = 100)
## self.tree.column("House Number", width = 60)
## self.tree.column("Street Name", width = 60)
## self.tree.column("Town Or City Name", width = 60)
## self.tree.column("PostCode", width = 60)
## self.tree.column("MobilePhoneNumber", width = 60)
self.tree.heading("StudentID",text="StudentID")
self.tree.heading("First Name",text="First Name")
self.tree.heading("Last Name",text="Last Name")
## self.tree.heading("House Number",text="House Number")
## self.tree.heading("Street Name",text="Street Name")
## self.tree.heading("Town Or City Name",text="Town Or City Name")
## self.tree.heading("PostCode",text="PostCode")
## self.tree.heading("MobilePhoneNumber",text="MobilePhoneNumber")
self.tree["show"] = "headings"
yscrollbar = Scrollbar(frame2, orient='vertical', command=self.tree.yview)
xscrollbar = Scrollbar(frame2, orient='horizontal', command=self.tree.xview)
self.tree.configure(yscroll=yscrollbar.set, xscroll=xscrollbar.set)
yscrollbar.grid(row=1, column=5, padx=2, pady=2, sticky=NS)
self.tree.grid(row=1,column=0,columnspan =5, padx=2,pady=2,sticky =NSEW)
self.tree.bind("<Double-1>",lambda event :self.OnDoubleClick(event))
def OnDoubleClick(self, event):
frame3 = tk.LabelFrame(root, text="frame1", width=300, height=130, bd=5)
frame3.grid(row=2, column=0, columnspan=3, padx=8)
self.message=StringVar()
self.message.set("")
self.lblupdate = Label(frame3, textvariable = self.message).grid(row=0,column=0,sticky=W)
curItem = self.tree.focus()
contents =(self.tree.item(curItem))
StudentDetails = contents['values']
print(StudentDetails)
self.tStudentID=StringVar()
self.tFirstName = StringVar()
self.tLastName = StringVar()
self.tHouseNumber = StringVar()
self.tStreetName = StringVar()
self.tTownOrCityName = StringVar()
self.tPostCode = StringVar()
self.tEmail = StringVar()
self.tMobilePhoneNumber = StringVar()
self.tStudentID.set(StudentDetails[0])
self.tFirstName.set(StudentDetails[1])
self.tLastName.set(StudentDetails[2])
self.tHouseNumber.set(StudentDetails[3])
self.tStreetName.set(StudentDetails[4])
self.tTownOrCityName.set(StudentDetails[5])
self.tPostCode.set(StudentDetails[6])
self.tEmail.set(StudentDetails[7])
self.tMobilePhoneNumber.set(StudentDetails[8])
self.inst_lbl0 = Label(frame3, text = "Student ID").grid(row=5,column=0,sticky=W)
self.StudentID = Label(frame3, textvariable=self.tStudentID).grid(row =5,column=1,stick=W)
self.inst_lbl1 = Label(frame3, text = "First Name").grid(row=6,column=0,sticky=W)
self.NFirstName = Entry(frame3, textvariable=self.tFirstName).grid(row =6,column=1,stick=W)
self.inst_lbl2 = Label(frame3, text = "Last Name").grid(row=7,column=0,sticky=W)
self.NLastName = Entry(frame3, textvariable=self.tLastName).grid(row =7,column=1,stick=W)
self.inst_lbl3 = Label(frame3, text = "House Number").grid(row=8,column=0,sticky=W)
self.HouseNumber = Entry(frame3,textvariable=self.tHouseNumber).grid(row=8,column=1,sticky=W)
self.inst_lbl4 = Label(frame3, text = "Street Name").grid(row=9,column=0,sticky=W)
self.StreetName =Entry(frame3,textvariable=self.tStreetName).grid(row=9,column=1,sticky=W)
self.inst_lbl5 = Label(frame3, text = "Town or City Name").grid(row=10,column=0,sticky=W)
self.TownOrCityName =Entry(frame3,textvariable=self.tTownOrCityName).grid(row=10,column=1,sticky=W)
self.inst_lbl6 = Label(frame3, text = "Postcode").grid(row=11,column=0,sticky=W)
self.PostCode = Entry(frame3,textvariable=self.tPostCode).grid(row=11,column=1,sticky=W)
self.inst_lbl7 = Label(frame3, text = "Email").grid(row=12,column=0,sticky=W)
self.Email =Entry(frame3,textvariable=self.tEmail).grid(row=12,column=1,sticky=W)
self.inst_lbl8 = Label(frame3, text = "Mobile phonenumber").grid(row=13,column=0,sticky=W)
self.MobilePhoneNumber =Entry(frame3,textvariable=self.tMobilePhoneNumber).grid(row=13,column=1,sticky=W)
self.btnSaveChanges = Button(frame3, text = "save changes",padx=80,pady=10,command = lambda:self.SaveChanges()).grid(row=14,column=0,sticky=W)
self.btnSaveChanges = Button(frame3, text = "delete record",padx=80,pady=10,command = lambda:self.DeleteRecord()).grid(row=14,column=1,sticky=W)
def search(self):
FirstName = self.fn_txt.get()
LastName = self.ln_txt.get()
with sqlite3.connect("GuitarLessons.db") as db:
cursor = db.cursor()
cursor.row_factory = sqlite3.Row
sql = "select StudentID,FirstName,LastName,HouseNumber,StreetName,TownOrCityName,PostCode,Email,MobilePhoneNumber"\
" from tblStudents"\
" where FirstName like ?"\
" and LastName like ?"
cursor.execute(sql,("%"+FirstName+"%","%"+LastName+"%",))
StudentList = cursor.fetchall()
print(StudentList)
self.loadStudents(StudentList)
def loadStudents(self,StudentList):
for i in self.tree.get_children():
self.tree.delete(i)
for student in StudentList:
self.tree.insert("" , 0,values=(student[0],student[1],student[2],student[3],student[4],student[5],student[6],student[7],student[8]))
def SaveChanges(self):
valid = True
self.message.set("")
NFirstName = self.tFirstName.get()
NLastName = self.tLastName.get()
NHouseNumber = self.tHouseNumber.get()
NStreetName = self.tStreetName.get()
NTownOrCityName = self.tTownOrCityName.get()
NPostCode = self.tPostCode.get()
NEmail = self.tEmail.get()
NMobilePhoneNumber = self.tMobilePhoneNumber.get()
StudentID = self.tStudentID.get()
if NFirstName == "" or NLastName == "" or NEmail == "" or NMobilePhoneNumber == "":
valid = False
self.message.set('missing details,first name,last name,phone number, email are all needed')
if not Utilities.is_phone_number(NMobilePhoneNumber ):
valid = False
self.message.set('invalid mobile phone number')
if not Utilities.is_postcode(NPostCode):
valid = False
self.message.set('invalid postcode')
if not Utilities.is_email(NEmail):
valid = False
self.message.set('invalid email')
if NHouseNumber != "":
if int(NHouseNumber) < 0:
self.message.set('invalid house number')
if valid == True:
with sqlite3.connect("GuitarLessons.db") as db:
cursor = db.cursor()
sql = "update tblStudents set FirstName =?,LastName=?,HouseNumber=?,StreetName=?,TownOrCityName=?,PostCode=?,Email=?,MobilePhoneNumber=? where StudentID=?"
cursor.execute(sql,(NFirstName,NLastName,NHouseNumber,NStreetName,NTownOrCityName,NPostCode,NEmail,NMobilePhoneNumber,StudentID))
db.commit()
self.message.set("student details updated")
def DeleteRecord(self):
StudentID = self.tStudentID.get()
#StudentID = int(StudentID)
with sqlite3.connect("GuitarLessons.db") as db:
cursor = db.cursor()
sql = "delete from tblStudents where StudentID = ?"
cursor.execute(sql,(StudentID))
db.commit()
self.tlabeupdate.set("student details deleted")
root = Tk()
root.title("booking system")
root.geometry("800x800")
root.configure(bg="white")
app = Application(root)
root.mainloop()
EDIT
when i was copyign and pasting the rest of my code that i forgot to put in the original post i found that it only stops working if i open it through the student menu(separate peice of code) but it works if i dont go through the menu
You must call mainloop() on the root window so that your program can process events.
You create LabelFrames in the parent called root, but root does not exist. To correct it pass master to the function, which receives it as root
class Application():
""" Binary to Decimal """
def __init__(self, master):
""" Initialize the frame. """
self.create_GUI(master)
def create_GUI(self, root):
frame1 = tk.LabelFrame(root, text="frame1", width=300, height=130, bd=5)

Discussion with tkinter

from tkinter import *
window = Tk()
ia_answers= "trolol"
input_frame = LabelFrame(window, text="User :", borderwidth=4)
input_frame.pack(fill=BOTH, side=BOTTOM)
input_user = StringVar()
input_field = Entry(input_frame, text=input_user)
input_field.pack(fill=BOTH, side=BOTTOM)
ia_frame = LabelFrame(window, text="Discussion",borderwidth = 15, height = 100, width = 100)
ia_frame.pack(fill=BOTH, side=TOP)
user_says = StringVar()
user_text = Label(ia_frame, textvariable=user_says, anchor = NE, justify = RIGHT, bg="white")
user_text.pack(fill=BOTH, side=TOP)
ia_says = StringVar()
ia_text = Label(ia_frame, textvariable=ia_says, anchor = W, justify = LEFT, bg="white")
ia_text.pack(fill=BOTH, side=BOTTOM)
def Enter_pressed(event):
"""Took the current string in the Entry field."""
input_get = input_field.get()
input_user.set("")
user_says.set(input_get + "\n\n")
ia_says.set(ia_answers)
input_field.bind("<Return>", Enter_pressed)
window.mainloop()
Hi, i am trying to build a discussion Bot.
When I execute the code, the question in the input field and the answer get displayed correctly.
The problem is after entering the next sentence, the previous question/answer gets removed. Here is an example:
Hello Bot
Hello User
(then the text disappears)
How are you
Fine thank you
What i want :
Hello Bot
Hello User
(then the text stays in the frame)
How are you
Fine thank you
The issue occurs in line -
user_says.set(input_get + "\n\n")
ia_says.set(ia_answers)
You are replace users_says.set() and ia_says.set() resets the complete Labels , with the new value. Instead you should get the old value and append the new value to it and set it back, Example -
user_says.set(user_says.get() + input_get + "\n")
ia_says.set(ia_says.get() + ia_answers + "\n")
Or you can also create a new label for each new event and add it to the LabelFrame . Example -
from tkinter import *
window = Tk()
ia_answers= "trolol\n"
input_frame = LabelFrame(window, text="User :", borderwidth=4)
input_frame.pack(fill=BOTH, side=BOTTOM)
input_user = StringVar()
input_field = Entry(input_frame, text=input_user)
input_field.pack(fill=BOTH, side=BOTTOM)
ia_frame = LabelFrame(window, text="Discussion",borderwidth = 15, height = 100, width = 100)
ia_frame.pack(fill=BOTH, side=TOP)
user_says = StringVar()
user_text = Label(ia_frame, textvariable=user_says, anchor = NE, justify = RIGHT,
bg="white")
user_text.pack(fill=X)
ia_says = StringVar()
ia_text = Label(ia_frame, textvariable=ia_says, anchor = NW, justify = LEFT, bg="white")
ia_text.pack(fill=X)
user_texts = []
ia_texts = []
user_says_list = []
ia_says_list = []
def Enter_pressed(event):
"""Took the current string in the Entry field."""
input_get = input_field.get()
input_user.set("")
user_says1 = StringVar()
user_says1.set(input_get + "\n")
user_text1 = Label(ia_frame, textvariable=user_says1, anchor = NE, justify = RIGHT,
bg="white")
user_text1.pack(fill=X)
user_texts.append(user_text1)
user_says_list.append(user_says1)
ia_says1 = StringVar()
ia_says1.set(ia_answers)
ia_text1 = Label(ia_frame, textvariable=ia_says1, anchor = NW, justify = LEFT,
bg="white")
ia_text1.pack(fill=X)
ia_texts.append(ia_text1)
ia_says_list.append(ia_says1)
input_field.bind("<Return>", Enter_pressed)
window.mainloop()

Categories