get certain cell in tkinter grid - python

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

Related

How to remove the white lines on the sides of Tkinter?

enter image description here
As you can see in the screenshot, my program has white lines on the left and top, how can I remove them? I would like them not to be there at all.
import ctypes as ct
from tkinter import *
def dark_title_bar(window):
window.update()
DWMWA_USE_IMMERSIVE_DARK_MODE = 20
set_window_attribute = ct.windll.dwmapi.DwmSetWindowAttribute
get_parent = ct.windll.user32.GetParent
hwnd = get_parent(window.winfo_id())
rendering_policy = DWMWA_USE_IMMERSIVE_DARK_MODE
value = 2
value = ct.c_int(value)
set_window_attribute(hwnd, rendering_policy, ct.byref(value), ct.sizeof(value))
win = Tk()
background_menu = PhotoImage(file="background-menu.png")
canvas_authorization = Canvas(win, width=1280, height=720)
canvas_authorization.grid()
canvas_authorization.create_image(640, 360, image=background_menu)
dark_title_bar(win)
win.geometry("1280x720")
win.geometry(str(win.winfo_width()+1) + "x" + str(win.winfo_height()+1))
#Returns to original size
win.geometry(str(win.winfo_width()-1) + "x" + str(win.winfo_height()-1))
win.geometry("1280x720")
win.mainloop()

Python Tkinter:Frames are not going under each otheer

I was making a simple tkinter GUI which has scrolling frames in it but it is not being so perfect for me.At first I used only one frame, but however I found out that frames have a limit on the no. of widgets they can hold,so I started using multiple frames. However I got this problem:the frames are not going in the direction I wanted.I wanted the frames to go under the previous frame ,however the frames are going one above the other here is a screenshot of the same:
(Frame 0 is the first Frame)
Here is the code(I have only kept the important portion)
i=0
image_no=0
for video in videos:
u = urllib.request.urlopen(video["thumbnail"]["thumbnails"][0]["url"])
raw_data = u.read()
u.close()
im = Image.open(BytesIO(raw_data))
image = ImageTk.PhotoImage(im.resize((470,210)))
a.append(image)
tk.Label(fr[i], image=a[image_no]).pack()
image_no+=1
tk.Label(fr[i], text=("Video:"+str(image_no)+" frame:"+str(i)),wraplength=470,font=("ariel",11,"bold"),bg="white").pack()
tk.Label(fr[i], text=video["title"]["accessibility"]["accessibilityData"]['label'].replace(video["title"]["runs"][0]["text"],""),wraplength=470,font=("ariel",10),bg="white",fg="grey").pack(anchor="w")
canvas.configure(yscrollcommand=scroll_y.set)
canvas.configure(scrollregion=canvas.bbox("all"))
print(image_no)
print(video["title"]["runs"][0]["text"])
if image_no%10==0:
time.sleep(3)
if image_no%110==0:
i+=1
if image_no%440==0:
break
Is there any way I could make it go downwards?
Edit:
Here is the screenshot of the frame limit
the black area is of the canvas
Here is a link to question tkinter maximum canvas size?
I've modified the code due to the possibility that the number of images may be responsible or the canvas may have some maximum height.
This will now fill the entire canvas height with images, each with a 10 point space between.
I've updated it for python 3.x and increased height to 100000!
Works without problems.
Choose your own image (gif or png)
import tkinter as tk
from tkinter import filedialog as fido
root = tk.Tk()
root.rowconfigure(0, weight = 1)
root.columnconfigure(0, weight = 1)
picture = fido.askopenfilename(title = "Pick a pic")
iconimage = tk.PhotoImage(file = picture)
wide, high = iconimage.width(), iconimage.height()
frame = tk.LabelFrame(root, labelanchor = "s", text = "0|0")
frame.grid(row = 0, column = 0, sticky = "nsew")
frame.rowconfigure(0, weight = 1)
frame.columnconfigure(0, weight = 1)
cv = tk.Canvas(
frame, width = 1200, height = 700,
scrollregion = "0 0 2000 100000")
cv.grid(row = 0, column = 0, sticky = "nsew")
vscrollbar = tk.Scrollbar(
frame, orient = "vertical", command = cv.yview)
vscrollbar.grid(row = 0, column = 1, sticky = "ns")
cv.config(yscrollcommand = vscrollbar.set)
def rowcol(ev):
frame["text"] = f"{cv.canvasx(ev.x)} | {cv.canvasy(ev.y)}"
cv.bind("<Motion>", rowcol)
root.update()
testimage = []
for pos in range( 0, 100000 - high - 10, high + 10):
testimage.append(cv.create_image(100, pos, anchor = "nw", image = iconimage))
print(f"Number of images = {len(testimage)}, width = {wide}, height = {high}")
root.mainloop()
So it doesn't seem to be a limitation of Canvas height or number of images displayed.

Tkinter canvas image transition

I want to have some transition to show the images in the canvas, I'm using Tkinter and I'm looping through the images to show them on the canvas but I need to have some transition while switching among the images.
I'm using canvasName.create_image method for showing the images. Need a way to show them smoothly.
Here is my code:
def Multi_view_rotate():
window.geometry(str(scr_w)+"x"+str(scr_h)+"+0+0")
z_out = 20
global timeSleep
timeSleepVal = int(timeSleep.get())
global footerPath
footerPath = footerPath.get()
#geting director from entry boxes
global portDirEntry
portDirEntry = portDirEntry.get()
global colorEntry
bgcolor = colorEntry.get()
allPaths = getPaths(portDirEntry)
#directory = r"C:\Users\DotNet\Desktop\Ragazinana Data reduced\diashow\4 Random\Landschaft"
#Get paths
pathsPrt = allPaths[0]
pathsLand = allPaths[1]
#read the image
#call the function to get the picture object with new size
global numOfImagesPort
global numOfImagesLand
#footer path
#footerPath = "C:/Users/DotNet/Desktop/Ragazinana Data reduced/diashow/ragaziana_s.jpg"
#Footer will take 8% of the screen width
per_w_footer = cal_per_num(8, scr_w)
# Footer Image operations
canvasFoot = Canvas(window,width=per_w_footer, height=scr_h, bg=bgcolor, highlightthickness=1, highlightbackground=bgcolor)
canvasFoot.grid(row=0, column=0)
#footerImg = get_img_fit_size(footerPath, scr_h, per_w_footer, True)
footerImg1 = Image.open(footerPath)
footerImg2 = footerImg1.transpose(Image.ROTATE_270)
footerImg3 = footerImg2.resize((int(per_w_footer),int(scr_h)), Image.ANTIALIAS)
footerImg = ImageTk.PhotoImage(footerImg3)
footer = canvasFoot.create_image(per_w_footer/2,scr_h/2,anchor=CENTER, image=footerImg)
while(numOfImagesPort<=len(pathsPrt)-1 or numOfImagesLand<=len(pathsLand)-1 ):
pathPort = pathsPrt[numOfImagesPort]
#increase the index to get the next file in the next loop
numOfImagesPort=numOfImagesPort+1
#if the next photo is out of bound then assign it to the first index
if(numOfImagesPort >= len(pathsPrt)):# if total is 5 pic, 1st loop 0 > 6 /reset the loop
numOfImagesPort=0
# each image will take as following in percentage
per_w_imgs_portriate = cal_per_num(42, scr_w)
per_w_imgs_landscape= cal_per_num(50, scr_w)
#Create the canvases
canvasPort = Canvas(window,width=per_w_imgs_portriate, height=scr_h, bg=bgcolor, highlightthickness=10, highlightbackground=bgcolor)
#gird plays the canvas without it the canvas will not work
canvasPort.grid(row=0, column=1)
#in order to make the picture fit in the rotated state in the half of the screen
# we make the get_img_fit_size adjust it to us to that size by providing
# screen hight as a width and half of the screen with as a height
imgPort = get_img_fit_size(pathPort, scr_h, per_w_imgs_landscape, True)
portImgCanvas = canvasPort.create_image(int(scr_w/4.3),int(scr_h/2),anchor=CENTER, image=imgPort)**
window.update()
time.sleep(timeSleepVal/2)
# Landscape image
pathLand = pathsLand[numOfImagesLand]
numOfImagesLand = numOfImagesLand+1
if(numOfImagesLand >= len(pathsLand)):
numOfImagesLand=0
canvasLand = Canvas(window,width=per_w_imgs_landscape, height=scr_h, bg=bgcolor, highlightthickness=10, highlightbackground=bgcolor)
canvasLand.grid(row=0, column=2)
imgLand = get_img_fit_size(pathLand, scr_h, per_w_imgs_portriate, True)
landImgCanvas = canvasLand.create_image(int(scr_w/4.5),int(scr_h/2),anchor=CENTER, image=imgLand)
window.update()
time.sleep(timeSleepVal/2)
window.mainloop()
I don't think there is something like this built into Tkinter.PhotoImage, but you could manually create a "fade" transition by randomly selecting pixels and setting them to the color values of the next image:
import tkinter, random
root = tkinter.Tk()
c = tkinter.Canvas(root, width=800, height=400)
c.pack()
img_a = tkinter.PhotoImage(file="a.gif")
img_b = tkinter.PhotoImage(file="b.gif")
i = c.create_image(0, 0, image=img_a, anchor="nw")
pixels = [(x, y) for x in range(img_a.width()) for y in range(img_a.height())]
random.shuffle(pixels)
def fade(n=1000):
global pixels, i
for _ in range(min(n, len(pixels))):
x, y = pixels.pop()
col = "#%02x%02x%02x" % img_b.get(x,y)
img_a.put(col, (x, y))
c.delete(i)
i = c.create_image(0, 0, image=img_a, anchor="nw")
if pixels:
c.after(1, fade)
fade()
root.mainloop()
This is slow, though. The after with 1 ms is only to keep the UI from freezing (don't use while with time.sleep in Tkinter!). For a smoother transition, instead of replacing pixel values you might gradually shift all pixels towards the values in the next image, but that will be even slower since you'd change all pixels in each step.
Instead of pure tkinter, we can try it wit PIL and numpy, but it is not noticeably faster, and least not the way I did it:
import numpy as np
from PIL import Image, ImageTk
from itertools import islice
...
arr_a = np.array(Image.open("a.gif").convert("RGB"))
arr_b = np.array(Image.open("b.gif").convert("RGB"))
img = ImageTk.PhotoImage(Image.fromarray(arr_a, mode="RGB"))
i = c.create_image(0, 0, image=img, anchor="nw")
h, w, _ = arr_a.shape
pixels = [(x, y) for x in range(w) for y in range(h)]
random.shuffle(pixels)
def fade(k=0, n=1000):
global i, img
X, Y = zip(*islice(pixels, k, k+n))
arr_a[Y,X] = arr_b[Y,X]
c.delete(i)
img = ImageTk.PhotoImage(Image.fromarray(arr_a, mode="RGB"))
i = c.create_image(0, 0, image=img, anchor="nw")
if k + n < w * h:
c.after(1, fade, k+n, n)
fade()
root.mainloop()
However, this also allows us to replace entire lines at once. The effect is not quite as nice, but it is much faster (also note changed n and if condition).
...
h, w, _ = arr_a.shape
lines = list(range(h))
random.shuffle(lines)
def fade(k=0, n=10):
global i, img
Y = lines[k:k+n]
arr_a[Y] = arr_b[Y]
...
if k + n < h:
c.after(1, fade, k+n, n)
...
This can also easily be transformed to a vertical or horizontal slide transition by simply not shuffling the lines (for columns, use arr_a[:,X] = arr_b[:,X]).

When use image in tk Button, Button disappear

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.

How to make simple GUI graph with Linear Equation

I am a beginner programmer. I have a task to make a GUI with a linear equation y=mx+b and a set of parameters where I can change the m and b values. I have both matplotlib and numpy. I also have tkinter for the GUI. This is what i have so far i edited my friends code on a coordinate GUI.
def onButtonValChange():
if X1.get() != '':
x[0] = float(X1.get())
if Y1.get() != '':
y[0] = float(Y1.get()
def createGraph(x,y):
graphRoot = Tk.Tk()
graphRoot.wm_title("Your Graph")
graphRoot.resizable(0,0)
f = Figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(111)
a.plot(x, y)
canvas = FigureCanvasTkAgg(f, master=graphRoot)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
x = [1]
y = [1]
ButtonChangeValues = Tk.Button(root, text="Submit Change", command=onButtonValChange)
ButtonChangeValues.grid(row=11, columnspan=3)
ButtonCreateGraph = Tk.Button(root, text="Create This Graph", command=lambda: createGraph(x, y))
ButtonCreateGraph.grid(row="15", columnspan=3)
Tk.mainloop()
So here is some code that i use its a moving line graph but you could adapt the code to move only when you change the equation. all you would have to do is populate the lists of x0Coords y0Coords and xy0Coords with the right mx+b formula
# Run from IDLE or LXTerminal not IDLE 3
# for import spidev to work, must run as python (v2) not python3
from Tkinter import * #to run on python 2, use Tkinter, for python3 use tkinter
import math
from datetime import datetime, timedelta
import numpy as np
import spidev
#--------------------- variables -------------------------
#---user defined settings
screenWidth = 450
resolution = 5 #number of pixels between data points, for visual purposes only
samplePeriod = 100 #milliseconds, time between data points written to txt file
timeRange = .5 #minutes
#---end user settings
baseTime = int(timeRange*60*1000/screenWidth)
startTime = datetime.now()
nl = "\n"
root = Tk()
root.title("Simple GUI")
root.geometry("500x300") #widthxheight
C = Canvas(root, bg = "gray", height = 250, width = screenWidth)
x0Coords = []
y0Coords = []
xy0Coords = []
coordLength = int(screenWidth/resolution)
#---initiation of lists
for i in range(0,coordLength):
x0Coords.append(i*resolution)
y0Coords.append(125)
xy0Coords.append(0)
xy0Coords.append(0)
#putting X and Y corrdinites in a list
def coordinate():
global x0Coords, y0Coords, xy0Coords
for i in range(0,coordLength*2,2):
xy0Coords[i] = x0Coords[i/2]
xy0Coords[i+1] = y0Coords[i/2]
#print(xy0Coords)
#---End initiation of lists
c0 = C.create_rectangle(0,0,20,50)
cl0 = C.create_line(xy0Coords)
pressure = Label(root, text="test")
pressure.pack()
spi_0 = spidev.SpiDev()
spi_0.open(0, 0)
#--------------------------- End of Variables -------------------------
#--------------------------- Definitions ------------------------------
#shifts y values down in index in array to represent time moved forward
def shiftCoords(nextValue):
global y0Coords, xy0Coords
y0Coords.pop(0)
y0Coords.append(nextValue)
coordinate()
#updates the GUI based on the new time
def move_time():
global c0,cl0,xy0Coords, resolution, baseTime
C.delete(c0)
C.delete(cl0)
c0 = C.create_rectangle(0,0,20,int(float(readadc_0(0))/1023*250))
shiftCoords(125-int(float(readadc_0(0))/1023*125))
cl0 = C.create_line(xy0Coords)
#print(float(readadc_0(0))/1023*250)
root.title("V= " + str(round(3.3*float(readadc_0(0))/1023,2)))
root.after(baseTime*resolution,move_time)
C.pack()
root.after(baseTime,move_time)
root.after(samplePeriod,writeData)
root.mainloop()

Categories

Resources