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:
Related
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
I apologize in advance for my bad English...
I am new in the programming world so I don't really know what I'm doing. I'm trying to make a basic address book in Python, Tkinter. I managed somehow to write code to add records in the database but cannot write it to delete or edit selected records. Help would be appreciate
import datetime
import tkinter
from tkinter import *
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
import sqlite3
def date_for_humans():
date = datetime.datetime.now().date()
date = str(date)
x = date.split("-")
return x[2] + "." + x[1] + "." + x[0] + "."
# creating windows for show contact
def add():
kontakti = Toplevel()
kontakti.title("Lista kontakta")
kontakti.iconbitmap(r"phonebookicon.ico")
kontakti.geometry("400x500")
kontakti.resizable(False, False)
def submit():
# create data base or connect to one
conn = sqlite3.connect("Imenik.db")
# create cursor
c = conn.cursor()
# insert into a table
c.execute("INSERT INTO Kontakti VALUES (:f_name, :l_name, :number)",
{
"f_name": f_name.get(),
"l_name": l_name.get(),
"number": number.get()
})
# commint changes
conn.commit()
conn.close()
f_name.delete(0,END)
l_name.delete(0, END)
number.delete(0, END)
# creating and coloring top frame
topframe = tk.Frame(kontakti, height=150, bg="#ffffff")
topframe.pack(fill=X)
# creating and coloring bottom farame
bottomframe = tk.Frame(kontakti, height=350, bg="#34ebeb")
bottomframe.pack(fill=X)
# creating text at the top of app:
text2 = Label(kontakti, text="DODAVANJE KONTAKTA", font="ariel 15 bold", bg="#ffffff", fg="black")
text2.place(x=80, y=20)
# creating close button
button1 = Button(kontakti, text="Zatvori prozor", bg="white", fg="black",
activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=kontakti.destroy)
button1.place(x=295, y=465)
# create text boxes
f_name = Entry(kontakti, width=30)
f_name.place(x=80, y=200, height=20)
l_name = Entry(kontakti, width=30)
l_name.place(x=80, y=230, height=20)
number = Entry(kontakti, width=30)
number.place(x=80, y=260, height=20)
# create text box labels
f_name_label = Label(kontakti, text="Ime", bg="#34ebeb")
f_name_label.place(x=20, y=200)
l_name_label = Label(kontakti, text="Prezime", bg="#34ebeb")
l_name_label.place(x=20, y=230)
number_label = Label(kontakti, text="Broj", bg="#34ebeb")
number_label.place(x=20, y=260)
# create sumbit button
submint_btn = Button(kontakti, text="Dodaj kontakt", bg="white", fg="black",
activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=submit)
submint_btn.place(x=40, y=320)
def edit():
c.execute("UPDATE Kontakti SET f_name=?, l_name=?, number=? WHERE f_name= ? AND l_name = ? AND number=?",
(new_value_for_f_name, new_value_for_l_name, new_value_for_number, f_name, l_name, number))
conn.commit()
def delete():
f_name = listbox.curselection()[0]
l_name = listbox.curselection()[1]
number = listbox.curselection()[2]
c.execute("DELETE * FROM Kontakti WHERE f_name = ? AND l_name = ? AND number = ?", (f_name, l_name, number))
conn.commit()
def leave():
root.destroy()
# creating a main window:
root = Tk()
root.title("Imenik App")
root.iconbitmap(r"phonebookicon.ico")
root.geometry("650x550")
root.resizable(False, False)
# creating and coloring top frame:
topFrame = tk.Frame(root, height=150, bg="#ffffff")
topFrame.pack(fill=X)
# creating and coloring bottom frame:
bottomFrame = tk.Frame(root, height=500, bg="#34ebeb")
bottomFrame.pack_propagate(False)
bottomFrame.pack(fill=X)
listbox = Listbox(bottomFrame)
listbox.place(x=40, y=40, height=340, width=200)
scrollbar = Scrollbar(bottomFrame)
scrollbar.place(height=340, x=240, y=40)
# Insert elements into the listbox
conn = sqlite3.connect("Imenik.db")
c = conn.cursor()
a = c.execute("SELECT *,oid FROM Kontakti")
records = c.fetchall()
for record in records:
listbox.insert(END, str(record[0]) + " " + str(record[1]))
listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)
# creating text at the top of app:
text1 = Label(root, text="IMENIK", font="ariel 35 bold", bg="#ffffff", fg="black")
text1.place(x=240, y=40)
# displaying date and time at the top of app:
datel = Label(root, text="Danasnji datum: " + date_for_humans(), font="ariel 10 bold", bg="#ffffff", fg="black")
datel.place(x=450, y=125)
# displaying icon at the top of the app:
image1 = Image.open("phonebook1.png")
image1 = image1.resize((90, 90), Image.ANTIALIAS)
image = ImageTk.PhotoImage(image1)
label1 = tkinter.Label(image=image, bg="#ffffff")
label1.image = image
label1.place(x=80, y=30)
conn.commit()
conn.close()
'''
# create data base or connect to one
conn = sqlite3.connect("Imenik.db")
# create cursor
c = conn.cursor()
# create table
c.execute("""CREATE TABLE kontakti (
first_name txt,
last_name txt,
number integer
)""")
# commint changes
conn.commit()
conn.close()
'''
# adding button 1, add contacts
viewButton = Button(root, text="Dodaj kontakt", pady=10, padx=70, bg="white", fg="black",
activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=add)
viewButton.place(x=380, y=200)
# adding button 2, edit contacts
addButton = Button(root, text="Izmeni kontakt", pady=10, padx=67, bg="white", fg="black",
activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=edit)
addButton.place(x=380, y=260)
# adding button 3, delete contacts
deleteButton = Button(root, text="Obrisi kontakt", pady=10, padx=70, bg="white", fg="black",
activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=delete)
deleteButton.place(x=380, y=320)
# adding button 4, exit button
exitButton = Button(root, text="Izlaz", pady=5, padx=50, bg="white", fg="black",
activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=leave)
exitButton.place(x=505, y=510)
root.mainloop()
If anything is unclear please ask I really need help.
Thanks in advance!
Hi and welcome to Stack Overflow. For you to know which data is selected with the mouse, you can use the following way:
name_of_listbox.curselection()
This will return a list of the contents of the rows currently selected. It gives us a list because there is an option to select multiple rows of data in a ListBox.
You can iterate through each and grab the data out of them.
Store the data in a variable and use them for UPDATE and DELETE commands.
EDIT:
For deleting records:
f_name = listbox.curselection()[0]
l_name = listbox.curselection()[1]
number = listbox.curselection()[2]
c1.execute("DELETE * FROM Kontakti WHERE f_name = ? AND l_name = ? AND number = ?", (f_name, l_name, number))
conn1.commit()
For modifying the values:
c1.execute("UPDATE Kontakti SET f_name=?, l_name=?, number=? WHERE f_name= ? AND l_name = ? AND number=?",(new_value_for_f_name,new_value_for_l_name,new_value_for_number, f_name, l_name, number))
conn1.commit()
I quite did not get the way you were selecting first name, last name and number from a single listbox. So I have kept the name of the listbox the same.
You are using literal sql script and basically you can delete and update like below.
An advice ORM (Object Relational Mapping) is more effortless rather than raw query.
For Delete
DELETE <TableName> WHERE Id = <Value>
conn = sqlite3.connect("Imenik.db")
c = conn.cursor()
sql = "DELETE TableName WHERE Id = ?"
id = 1
c.execute(sql, (id,))
For Update
UPDATE <TableName> SET <ColumnName> = <NewValue> WHERE Id = <Value>
conn = sqlite3.connect("Imenik.db")
c = conn.cursor()
sql = "UPDATE TableName SET ColumnName = ? WHERE Id = ?"
id = 1
new_value = 'hello'
# params order left to right (important).
c.execute(sql, (new_value, id))
Is there a way to display data taken from my database in terms of table and that i can actually copy the individual contents of? using listbox and scrollbar currently i defined a function logs and gave looped thru it like this :
def logs():
log = Toplevel(root)
log.title('View all customers')
con = mysql.connect(host='localhost', user='root',
password='*****', database='BOOK')
c = con.cursor()
c.execute("SELECT * FROM library")
result = c.fetchall()
for index, x in enumerate(result):
num = 0
for y in x:
lookup_label = Label(log, text=y)
lookup_label.grid(row=index+1, column=num)
num +=1
l1 = Label(log,text='ID',font=font_text)
l2 = Label(log,text='S_ID',font=font_text)
l3 = Label(log,text='S_NAME',font=font_text)
l4 = Label(log,text='B_NAME',font=font_text)
l5 = Label(log,text='Date Taken',font=font_text)
l6 = Label(log,text='Date_Returned',font=font_text)
l7 = Label(log,text='Status',font=font_text)
btn_ext = Button(log,text='Exit',font=font_text,command=log.destroy,borderwidth=2,fg='#eb4d4b')
l1.grid(row=0,column=0,padx=20)
l2.grid(row=0,column=1,padx=20)
l3.grid(row=0,column=2,padx=20)
l4.grid(row=0,column=3,padx=20)
l5.grid(row=0,column=4,padx=20)
l6.grid(row=0,column=5,padx=20)
l7.grid(row=0,column=6,padx=20)
btn_ext.grid(row=index+2,columnspan=7,ipadx=540)
is there any alternatives to this if not listbox? to make tables? Thanks in advance :)
You can use ttk.Treeview to show data from database:
import tkinter as tk
from tkinter import ttk
import mysql.connector as mysql
def logs():
log = tk.Toplevel(root)
log.transient(root)
log.title('View all customers')
# setup treeview
columns = ('ID', 'S_ID', 'S_NAME', 'B_NAME', 'Date_Taken', 'Date_Returned', 'Status')
tree = ttk.Treeview(log, height=20, columns=columns, show='headings')
tree.grid(row=0, column=0, sticky='news')
# setup columns attributes
for col in columns:
tree.heading(col, text=col)
tree.column(col, width=100, anchor=tk.CENTER)
# fetch data
con = mysql.connect(host='localhost', user='root', password='******', database='BOOK')
c = con.cursor()
c.execute('SELECT * FROM library')
# populate data to treeview
for rec in c:
tree.insert('', 'end', value=rec)
# scrollbar
sb = tk.Scrollbar(log, orient=tk.VERTICAL, command=tree.yview)
sb.grid(row=0, column=1, sticky='ns')
tree.config(yscrollcommand=sb.set)
btn = tk.Button(log, text='Exit', command=log.destroy, width=20, bd=2, fg='#eb4d4b')
btn.grid(row=1, column=0, columnspan=2)
I have got 5 Frames. Frame1 contains the "New Target"-Button. Frame2 and-3 contain a list of Labels. The number of labels depens on how many entries are in the database. Frame4 and -5 contain buttons. Is it possible to add a scrollbar? I tried a lot to add a scrollbar but it doesn´t work.
Here is my code that doesn´t contain the scrollbar:
import tkinter as tk
import mysql.connector
from mysql.connector import Error
from datetime import datetime
import sys
import os
def ende():
main.destroy()
def restart():
main.destroy()
def delete(index):
print(labels[index * 2]["text"])
try:
connection = mysql.connector.connect(host='localhost',
database='databasename',
user='user',
password='password')
cursor = connection.cursor()
sql_Delete_query = """Delete from Targets where Titel = %s"""
cursor.execute(sql_Delete_query, (labels[index * 2]["text"],))
connection.commit()
print("Row deleted successfully ")
except mysql.connector.Error as error:
print("Failed to delete row from table: {}".format(error))
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
# Restarts the programm
python = sys.executable
os.execl(python, python, *sys.argv)
main = tk.Tk()
# Window size
main.geometry("400x400")
main.resizable(0, 0)
main['bg'] = 'red'
# Window position
w = main.winfo_reqwidth()
h = main.winfo_reqheight()
ws = main.winfo_screenwidth()
hs = main.winfo_screenheight()
x = (ws / 2) - (w / 2)
y = (hs / 2) - (h / 2)
main.geometry('+%d+%d' % (x, y))
fr1 = tk.Frame(main, borderwidth=2, relief="solid", bg="#271ee3", width=400, height=50)
fr2 = tk.Frame(main, borderwidth=2, relief="solid", bg="#0d9467", width=130, height=650)
fr3 = tk.Frame(main, borderwidth=2, relief="solid", bg="#3e1854", width=130, height=650)
fr4 = tk.Frame(main, borderwidth=2, relief="solid", bg="#3e1854", width=70, height=650)
fr5 = tk.Frame(main, borderwidth=2, relief="solid", bg="#3e1854", width=70, height=650)
fr1.pack()
fr2.pack(side="left")
fr3.pack(side="left")
fr4.pack(side="left")
fr5.pack(side="left")
fr2.grid_propagate(False)
fr2.grid_columnconfigure(0, weight=1)
fr3.grid_propagate(False)
fr3.grid_columnconfigure(0, weight=1)
fr4.grid_propagate(False)
fr4.grid_columnconfigure(0, weight=1)
fr5.grid_propagate(False)
fr5.grid_columnconfigure(0, weight=1)
# Button
tb = tk.Button(fr1, text="New Target", width=46, height=2, command=ende)
tb.grid(row=0)
# All targets - empty
labels = []
buttons = []
# Get current date
current_date = datetime.strptime(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), '%Y-%m-%d %H:%M:%S')
# Load all targets
def load_target():
try:
connection = mysql.connector.connect(host='localhost',
database='database',
user='user',
password='password')
sql_select_Query = "select * from Targets"
cursor = connection.cursor()
cursor.execute(sql_select_Query)
records = cursor.fetchall()
print("Total number of rows in ArmbandDB is: ", cursor.rowcount)
i = 0
if cursor.rowcount > 0:
for row in records:
date = current_date - row[2]
labels.append(tk.Label(fr2, text=row[1], pady=15))
labels.append(tk.Label(fr3, text=date, pady=15))
buttons.append(tk.Button(fr4, text="Restart", command=restart, pady=13))
buttons.append(tk.Button(fr5, text="Delete", command=lambda i=i: delete(i), pady=13))
i = i + 1
k = 0
for e in labels:
labels[k].grid(row=k, column=0, sticky='we')
k = k + 1
n = 0
for e in buttons:
buttons[n].grid(row=n, column=0, sticky='we')
n = n + 1
except Error as e:
print("Error reading data from MySQL table", e)
finally:
if (connection.is_connected()):
connection.close()
cursor.close()
print("MySQL connection is closed")
load_target()
print("Anzahl der labels2: ", str(len(labels)))
main.mainloop()
I suppose that the goal of your ScrollBar is to sroll the content of one of your frames.
If so, in tkinter there are no containter like a ScrollArea or ScrollPane in other languages. So you must create it yourself by using a canvas.
from tkinter import *
window = Tk()
frame_container=Frame(window)
canvas_container=Canvas(frame_container, height=100)
frame2=Frame(canvas_container)
myscrollbar=Scrollbar(frame_container,orient="vertical",command=canvas_container.yview) # will be visible if the frame2 is to to big for the canvas
canvas_container.create_window((0,0),window=frame2,anchor='nw')
for i in range(100):
Label(frame2, text=i).pack() # your labels, entries, whatever you whant inside your frame
frame2.update() # update frame2 height so it's no longer 0 ( height is 0 when it has just been created )
canvas_container.configure(yscrollcommand=myscrollbar.set, scrollregion="0 0 0 %s" % frame2.winfo_height()) # the scrollregion mustbe the size of the frame inside it,
#in this case "x=0 y=0 width=0 height=frame2height"
#width 0 because we only scroll verticaly so don't mind about the width.
canvas_container.pack(side=LEFT)
myscrollbar.pack(side=RIGHT, fill = Y)
frame_container.pack()
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()