I want to display multiple csv files (3 at least) in the same tkinter window but I have no clue how to do it. I have only found codes to display a single file in a window.
My current level in python is quite low (I'm a healthcare professional trying to do basic stuff) and it's basically adding together some code found online here and there but I still understand simple functions such as buttons and windows.
I have uploaded a picture to show more accurately what I'm aiming for: My goal in tkinter
Here is my current and my attempts so far:
from tkinter import *
import tkinter
import tkinter.ttk as ttk
from tkinter import Frame
import csv
root = tkinter.Tk()
root.title("Python - Healthcare continuity")
width = 500
height = 400
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width / 2) - (width / 2)
y = (screen_height / 2) - (height / 2)
root.geometry("%dx%d+%d+%d" % (width, height, x, y))
root.resizable(0, 0)
TableMargin = ttk.Frame(root)
TableMargin.grid(column=0, row=0, sticky=(N, W, E, S))
scrollbarx = Scrollbar(TableMargin, orient=HORIZONTAL)
scrollbary = Scrollbar(TableMargin, orient=VERTICAL)
# open file
with open("open(first.csv,'r+',encoding='utf-8')", newline = "") as file:
reader = csv.reader(file)
# r and c tell us where to grid the labels
r = 0
for col in reader:
c = 0
for row in col:
# i've added some styling
label = tkinter.Label(root, width = 10, height = 2, \
text = row, relief = tkinter.RIDGE)
label.grid(row = r, column = c)
c += 1
r += 1
with open("second.csv", newline = "") as file:
reader = csv.reader(file)
# r and c tell us where to grid the labels
r = 0
for col in reader:
c = 0
for row in col:
# i've added some styling
label = tkinter.Label(root, width = 10, height = 2, \
text = row, relief = tkinter.RIDGE)
label.grid(row = r, column = c)
c += 1
r += 1
with open("third.csv", newline = "") as file:
reader = csv.reader(file)
# r and c tell us where to grid the labels
r = 0
for col in reader:
c = 0
for row in col:
# i've added some styling
label = tkinter.Label(root, width = 10, height = 2, \
text = row, relief = tkinter.RIDGE)
label.grid(row = r, column = c)
c += 1
r += 1
root.mainloop()
Thank you for your help.
Related
This will draw a grid with same picture in every field. If I want to input row=x and col=y ex. x=3 y=2 and change picture only for that cell, how to do it?
Also if, I move that picture one or two fields how to get coordinates from cell where is it?
from tkinter import *
from PIL import Image, ImageTk
#main window
root = Tk()
root.title("toys ")
root.geometry("1000x800")
root.iconbitmap('Images/python.ico')
img1_temp = Image.open("Images/Spikes.png")
img1resized= img1_temp.resize((100,100))
img1 = ImageTk.PhotoImage(img1resized)
img2 = ImageTk.PhotoImage(Image.open("Images/Empty.png"))
imgr_temp = Image.open("Images/robot.png")
imgr_resized = imgr_temp.resize((100,100))
img_robot = ImageTk.PhotoImage(imgr_resized)
main_canvas = Canvas(root, width=600, height=600,scrollregion = "0 -200 200 0")
main_canvas.pack(pady=70)
cells = []
for r in range(6):
for c in range(6):
cells.append(Label(main_canvas, bd=5, height=80, width=80,
relief=RIDGE,padx=3, pady=3, image=img2).grid(row=r,column=c))
I tried this, but... not good
for cell in cells:
if type(cell) is Label:
row = 0
column = 0
image = img_robot
I have following Problem:
I have a table in which I documented which label for which article is needed.
The needed label should be updated automaticly when the entry is changed.
I look in a dataframe for the article number and give back the neede lable as picture.
For some reason it works only one time, and only if I enter with copy and paste the right article number. after the first time always the exept value is set to my variable.
I also don't understand the meaning of the *args as input for my search_label function. But without it gave me as soon as I entered something in the entry field the error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python\Python_3.9.1\lib\tkinter\__init__.py", line 1884, in __call__
return self.func(*args)
TypeError: search_label() takes 0 positional arguments but 3 were given
from multiprocessing import Process
import tkinter as tk
import pandas as pd
from PIL import ImageTk, Image
import os
import tkinter.messagebox as tkmb
def display_img(img_src):
global img
img = Image.open(img_src)
'size of the picture'
width_hight = 180
img = img.resize((width_hight, width_hight))
img = ImageTk.PhotoImage(img)
panel = tk.Label(root, image=img, bd=0)
'place in the middle of the window'
panel.place(x=width / 2 - width_hight / 2, y=row3)
def search_label(*args):
try:
artikel = entry_var.get()
artikel = str(artikel).upper()
print('entry= ', artikel)
#Needed cols of Excelfile
cols = ['Nr_','Reinigungsmittel']
global df
df = pd.DataFrame(df, columns=cols)
#For some reason there are always spaces at the end of the artikel in the dataframe
#remove spaces
df['Nr_'] = df['Nr_'].str.strip()
df.to_csv('Reinigungsmittel.csv', sep= ";", encoding='utf-8-sig')
df = df.set_index('Nr_')
#filter the dataframe only for artikel number
print('df:')
print(df)
#make entry capital letters
df_reinigungsmittel = df.loc[[artikel]]
#get only the cleanning article
cleaning_article = str(df_reinigungsmittel.iloc[0][0])
print('ergebnis:')
print(cleaning_article)
cleaning_article = str(cleaning_article).strip()
except:
cleaning_article = 'label search failed'
evaluation(cleaning_article)
def evaluation(cleaning_article):
print('input evaluation:',cleaning_article)
if cleaning_article == 'CMETHANOL':
cleaning_article = 'rot.png'
elif cleaning_article == 'CPROPANOL2':
cleaning_article = 'gruen.png'
elif cleaning_article == 'CPROPANOL':
cleaning_article = 'blau.png'
else:
cleaning_article = 'non.png'
print(cleaning_article)
display_img(cleaning_article)
#load dataframe when program is opend, so the dataframe doent' need to be loaded for each search
datasource = r'C:\Arbeit\scripte\Reinigungslabel\Reinigungslabel.xlsx'
datasource_csv = r'C:\Arbeit\scripte\Reinigungslabel\Reinigungsmittel.csv'
#df = pd.read_excel(datasource)
df = pd.read_csv(datasource_csv, sep =';')
# Window and layout settings
hight = 270
width = 250
column_space = 5
column1 = 10
width_column1 = width - 20
#start value of cleaning_article
cleaning_article = 'non.png'
hight_row = 30
space_row = 5
row1 = 10
row2 = row1 + hight_row + space_row
row3 = row2 + hight_row + space_row
root = tk.Tk()
entry_var = tk.StringVar()
entry_var.trace('w',search_label)
print(df)
root.title("Reinigungs Label V1.0")
# get screen width and height
# width of the screen
ws = root.winfo_screenwidth()
# height of the screen
hs = root.winfo_screenheight()
# calculate x and y coordinates for the Tk root window
x = ws - (1.05 * width)
y = 30
root.geometry('%dx%d+%d+%d' % (width, hight, x, y))
root.configure(bg='black', bd=0)
Canvas = tk.Canvas(root, height=hight, width=width).place()
frame_artikel = tk.Frame(root, bg = 'black')
frame_artikel.place(x=column1, y=row1, width=width_column1, height=hight_row)
entry_artikel = tk.Entry(frame_artikel, textvariable=entry_var, font=20)
entry_artikel.focus()
entry_artikel.place(relwidth=1, relheight=1)
root.mainloop()
Hi I am making a tkinter program but have run into this issue.
I am trying to use the grid method to center a load of buttons in the middle of the screen(The amount of buttons will vary dynamically) However I cant keep the buttons to a reasonable size I have followed the advice of someone who had a similar problem however I cant figure out what I am doing differently as it hasn't solved my issue.
Here is my code (it uses a directory pathway so it won't work for the reader but maybe you can spot what I am doing wrong)
ef open_win3():
global third_window
third_window = Toplevel()
third_window.config(height = 1800,width = 1800, bg = "chocolate1")
create_thirdwindow_button()
def create_thirdwindow_button():
bf = Frame(third_window,bg = "blue")
bf.grid(row=0, column=0,sticky="NESW")
bf.rowconfigure(0,weight = 1)
bf.columnconfigure(0,weight =1)
third_window.grid_rowconfigure(0, weight=1)
third_window.grid_columnconfigure(0, weight=1)
count = 0
x = 1
y = 0
mypath = "C:\\Users\\link\\OneDrive\\Desktop\\python stuff\\screenshot example\\Snapshots by catagory"
for g in listdir(mypath):
count += 1
for I in listdir(mypath):
btp = mypath +"\\"+str(I)
print(btp)
screenshot_snap = Button(bf,text = str(I),width = 1,height = 1, bg = "chocolate3",activebackground = "white",padx= 10,pady =10)
screenshot_snap.grid(sticky = "NESW")
screenshot_snap.grid_rowconfigure(0, weight=1)
screenshot_snap.grid_columnconfigure(0, weight=1)
x += 10
if y < count:
y += 1
Thanks a lot for any help!
Here is my code, you can ignore most of them but only see the last part which have #
import tkinter as tk
from PIL import ImageTk, Image
def bresize_and_load(path):
global bwidth, bheight
im = Image.open(path)
bwidth,bheight = im.size
resized = bresizemode(im, bwidth, bheight)
width,height = resized.size
return ImageTk.PhotoImage(resized)
def bresizemode(im, width, height):
if height / width >= ratio:
return im.resize((int(round((width / height) * usable_height)), usable_height),
Image.ANTIALIAS)
if height / width < ratio:
return im.resize((usable_width, (int(round((height / width) * usable_width)))),
Image.ANTIALIAS)
root = tk.Tk()
root.state("zoomed")
root.resizable(width=False, height=False)
frame = tk.Frame(root)
frame.grid(row = 0, column = 0, sticky = 'nsew')
tk.Grid.rowconfigure(root, 0, weight=1)
tk.Grid.columnconfigure(root, 0, weight=1)
row = 4
column = 5
for ro in range(row):
tk.Grid.rowconfigure(frame, ro, weight=1)
for co in range(column):
tk.Grid.columnconfigure(frame, co, weight=1)
root.update()
f_width = frame.winfo_width()
f_height = frame.winfo_height()
booklistbutton = []
for i in range(row):
for e in range(column):
bbutton = tk.Button(frame, height = int(f_height / row),
width = int(f_width / column))
bbutton.grid(row = i, column = e)
booklistbutton.append(bbutton)
root.update()
usable_width = booklistbutton[0].winfo_width()
usable_height = booklistbutton[0].winfo_height()
ratio = usable_height / usable_width
#here is image path
path = 'sample.jpg'
imm = []
#if it is range(20)(just = row * column) or less than column(here is 5), it work fine
for i in range(20):
imm.append(bresize_and_load(path))
booklistbutton[i].config(image = imm[i])
root.mainloop()
My question is, if you load image in button, but the number of imaged buttons is not less than column or equal row * column, the imaged buttons will disappear.
When range equal row * column(20):
When range is 6:
This is weird for me, does anyone have any idea?
Also, if you do not set button's width and height, they won't disappear. But buttons will little bigger than images.
(Posted solution on behalf of the OP).
I find the problem by myself, the problem is when I set the Buttons' size, it is chr size, but when I load a image, it change to pixel size, and at the same size number, chr size is bigger and bigger than pixel size, so the imaged button become too small to show.
from tkinter import *
from random import *
from functools import partial
class Game:
def __init__(self):
self.root = Tk()
self.frame = Frame(width = 574, height = 574)
self.frame.grid(columnspan = 30, rowspan = 30)
self.minex = []
self.miney = []
self.clickx = 0
self.clicky = 0
blank = PhotoImage(file = 'C:\\Users\\PC\\Desktop\\Python Programs\\Minesweeper\\blank.gif')
for i in range(0,30):
for j in range(0,30):
button = Button(width = 15, height = 15, padx = 2, pady = 2, image = blank, command = partial(self.click, j, i))
button.grid(row = i, column = j)
self.mine_place()
self.root.mainloop()
def mine_place(self):
for i in range(0,15):
self.minex.append(randint(1,30))
self.miney.append(randint(1,30))
def click(self, j, i):
miss = PhotoImage(file = 'C:\\Users\\PC\\Desktop\\Python Programs\\Minesweeper\\miss.gif')
hit = PhotoImage(file = 'C:\\Users\\PC\\Desktop\\Python Programs\\Minesweeper\\hit.gif')
for k in range(0, len(self.minex)):
if j + 1 == self.minex[k] and i + 1 == self.miney[k]:
button = Button(image = hit)
button.grid(row = i, column = j)
else:
button = Button(image = miss)
button.grid(row = i, column = j)
app = Game()
In self.click, when I wish to create a button with this image I am given a blank image. If I create a button in init, the image comes out just fine. What is wrong?..............................................................
It looks like you're images are getting garbage collected you need to save a reference to the images after using PhotoImage.
ie - you create the image blank so save a reference as self.blank= blank and use image = self.hit