Am trying to build a Tk project that displays data in a grid format to a Tk window, am fairly new to python Here's the project:
import pandas as pd
import time
from tabulate import tabulate
import csv
from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage
from pathlib import Path
data = {'name':'kangeso','msg':{'isSuccessful': True, 'statusCode': 200, 'message': [], 'result':{'closed_case':[{'id':[3456456675], 'subject': 'English', 'subject_id':2, 'created':76574767}], 'open_case': [], 'user_balance_id': 1089541798}}, 'request_id': ''}
actual = data['msg']
result = actual['result']
real = result['closed_case']
print(real)
kilo = tabulate(real, headers='keys',tablefmt = 'simple_grid')
print(kilo)
OUTPUT_PATH = Path(__file__).parent
ASSETS_PATH = OUTPUT_PATH / Path("Downloads")
def relative_to_assets(path: str) -> Path:
return ASSETS_PATH / Path(path)
window = Tk()
window.geometry("1440x700")
window.configure(bg = "#0F1014")
canvas = Canvas(
window,
bg = "#0F1014",
height = 700,
width = 1440,
bd = 0,
highlightthickness = 0,
relief = "ridge"
)
canvas.place(x = 0, y = 0)
write_to = canvas.create_rectangle(
0.0,
262.0,
1440.0,
700.0,
fill="#1A1E23",
outline="")
window.resizable(False, False)
window.mainloop()
this is the output without tkdesigner.ie print(kilo) it prints data in a grid format.
┌──────────────┬───────────┬──────────────┬───────────┐
│ id │ subject │ subject_id │ created │
├──────────────┼───────────┼──────────────┼───────────┤
│ [3456456675] │ English │ 2 │ 76574767 │
└──────────────┴───────────┴──────────────┴───────────┘
I would like to get values under subject_id, i used
(real[0])
but the data its just too much i have like hundreds them
I tried to display it using create_text but it gives an error that says int values must be either True or non True.
Related
tk.Label(self.info_frame, text = 'Paths:', font = 'bold').grid(column = 0, row = 0)
self.info_icon = tk.PhotoImage(file = r'info.png')
self.info_button = ttk.Button(self.info_frame, image = self.info_icon, command = lambda: messagebox.showinfo('messagebox', '''info'''))
self.info_button.image = self.info_icon
self.info_button.grid(column = 1, row = 0)
Code works well when when there is no theme . But it is not as I expect when applied ttkbootstrap theme
I did not find anything about this issue. Any way to fix? (Image is transparent)
I'm trying to make a memory game for fun and as a learning experience, and I've run into the issue where even with something like time.sleep(.5) I still can't get buttons to update correctly with a delay. In fact the second button seems to update to hidden as it's about to show the proper image. I'm assuming the issue lies somewhere in the buttonClicked() function.
I'm trying to figure out how I can make it show one button, then the second, then wait half a second and hide both. And if someone understands why this is happening or where I could look into the issue and read up on my own, that would be helpful.
Thanks.
from re import A
import time
import tkinter as tk
from tkinter import *
from typing_extensions import Self
from PIL import Image, ImageTk
import glob
import os, os.path
import numpy as np
from sqlalchemy import null
#resize images and button
imgButtonWidth = 100
imgButtonHeight = 100
imgButtonSize = (imgButtonWidth,imgButtonHeight)
#Set the height and width of the game by number of items.
width = 6
height = 6
#buttons = [[Button]*width]*height
#Total number of items 36 (0-35)
count = width*height-1
buttonList = []
#Will be a 2d array of [button, id]
answersList = []
clickedCount = 0
imgs = []
hiddenImg = null
# Create frame, set default size of frame and background color.
root = Tk()
root.title('Memory Game')
root.geometry(str(imgButtonWidth * (width+1)) + "x" + str(imgButtonHeight * (height+1)))
root.config(bg='darkblue')
frame = Frame(root, bg='darkblue')
# Fetch images from location and create a list of Image objects, then return.
def getImages():
imgs = []
path = "/home/paul/Programming/Python/MyMiniProjects/Mid/MemoryGame/"
valid_images = [".jpg",".gif",".png",".tga"]
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
if ext.lower() not in valid_images:
continue
imgs.append([Image.open(os.path.join(path,f)).resize(imgButtonSize), f])
return imgs + imgs
#Shuffle images for the game
imgs = getImages()
random.shuffle(imgs)
#Simple image to cover the tiles
hiddenImg = ImageTk.PhotoImage(Image.new('RGB', (imgButtonWidth, imgButtonHeight), (0,0,105)))
#Disable buttons after a match
def disable():
global clickedCount, answersList
clickedCount = 0
for a in answersList:
a[0]["state"] = "disabled"
a[0]["bg"] = "green"
answersList = []
#Hide buttons again
def hide():
global clickedCount, answersList
clickedCount = 0
for a in answersList:
#a[0].config(image = hiddenImg)
a[0]["image"] = hiddenImg
a[0]["state"] = "normal"
a[0]["bg"] = "white"
answersList = []
def wrong():
for a in answersList:
a[0]["bg"] = "red"
def buttonClicked(picture, id, button):
global clickedCount, answersList
print(clickedCount, len(answersList))
#print(button.image, "1", hiddenImg, picture)
if button.image is hiddenImg and clickedCount < 2:
button["image"] = picture
button["state"] = "disabled"
clickedCount += 1
answersList.append([button, id])
if len(answersList) == 2:
#Check id but make sure it's not the same button pressed twice
if answersList[0][1] is answersList[1][1]:#and answersList[0][0] is not answersList[1][0]:
disable()
else:
wrong()
hide()
#Create the actual buttons with their respective image
for h in range(height): #print(buttons[w][::],"\n")
newList = []
for w in range(width):
tempImage = imgs.pop(count)
picture = ImageTk.PhotoImage(tempImage[0])
id = tempImage[1]
button = Button(frame, image=hiddenImg, state=NORMAL, height=imgButtonHeight, width=imgButtonWidth)
#Need to split this up because of how python handles closures
button["command"] = lambda pic_temp=picture, id_temp=id, button_temp = button: buttonClicked(pic_temp, id_temp, button_temp)
button.image = hiddenImg
#buttons[w][h].name = str(w + h)
#buttons[w][h].grid(row=w, column=h, ipadx=random.randint(0,40), ipady=random.randint(0,40), padx=random.randint(0,5), pady=random.randint(0,5))
button.grid(row=h, column=w, padx=1, pady=1)
#Button(frame, image=picture).grid(row=w, column=h, ipadx=random.randint(0,40), ipady=random.randint(0,40), padx=random.randint(0,5), pady=random.randint(0,5))
count -= 1
# buttonList.append(buttons[h][w])
newList.append(button)
buttonList.append(newList)
# for y in range(height):
# for x in range(width):
# print(ButtonList[y][x])
# print("")
frame.pack(expand=True)
root.mainloop()```
I'm currently working on Tkinter and image stuff in a program. I want to display 9 images on the screen at the same time, but only one image(the last one)will appear on screen at one time. I've isolated the problem in this code so this is the fraction of my code that is causing this problem. The function "download" receives the images from the internet, and then "ext" takes the downloaded images and is supposed to put them on the screen, but not all of them go on.
import tkinter as tk
from tkinter.ttk import *
from threading import *
import random
from io import BytesIO
import urllib
import urllib.request
from PIL import Image, ImageTk
class CardClass:
def __init__(self):
self.master = tk.Tk()
self.master.attributes('-zoomed', True)
self.frame = Frame(self.master)
self.frame.pack()
self.state = False
self.master.attributes("-fullscreen", True)
self.but = Button(self.master, text="Print Images", command=self.Hand, pad = 150)
self.but.pack(pady = 12)
self.cardsList = ["https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg", "https://post.medicalnewstoday.com/wp-content/uploads/sites/3/2020/02/322868_1100-800x825.jpg", "https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg", "https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg", "https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg", "https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg", "https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg","https://post.medicalnewstoday.com/wp-content/uploads/sites/3/2020/02/322868_1100-800x825.jpg","https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg","https://post.medicalnewstoday.com/wp-content/uploads/sites/3/2020/02/322868_1100-800x825.jpg","https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg","https://post.medicalnewstoday.com/wp-content/uploads/sites/3/2020/02/322868_1100-800x825.jpg","https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg","https://post.medicalnewstoday.com/wp-content/uploads/sites/3/2020/02/322868_1100-800x825.jpg","https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg","https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg","https://www.thoughtco.com/thmb/O8fvqeXnAtOZ_L4eQ-aCRFKou_I=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/atlantic-bottlenose-dolphin--jumping-high-during-a-dolphin-training-demonstration-154724035-59ce93949abed50011352530.jpg"]
def Hand(self):
self.but.destroy()
self.newCard = random.sample(self.cardsList, k=9)
self.slot1 = self.cardsList[0]
self.slot2 = self.cardsList[1]
self.slot3 = self.cardsList[2]
self.slot4 = self.cardsList[3]
self.slot5 = self.cardsList[4]
self.slot6 = self.cardsList[5]
self.slot7 = self.cardsList[6]
self.slot8 = self.cardsList[7]
self.slot9 = self.cardsList[8]
self.ext()
def download(self, url, ex, ey):
print("here1")
with urllib.request.urlopen(url) as u:
raw_data = u.read()
img = Image.open(BytesIO(raw_data))
self.iimage = ImageTk.PhotoImage(img.resize((50,50), Image.ANTIALIAS))
lala = tk.Label(image=self.iimage)
lala.place(x=ex, y=ey)
return self.iimage
def ext(self):
self.download(self.newCard[0], 50, 150)
self.download(self.newCard[1], 100, 150)
self.download(self.newCard[2], 150, 150)
self.download(self.newCard[3], 200, 150)
self.download(self.newCard[4], 150, 150)
self.download(self.newCard[5], 300, 150)
self.download(self.newCard[6], 350, 150)
self.download(self.newCard[7], 400, 150)
self.download(self.newCard[8], 450, 150)
if __name__ == '__main__':
w = CardClass()
w.master.mainloop()
Does anybody know why this is happening? Thank you!
I don't think I understand why this should be, but the problem is, in fact, that the ImageTk.PhotoImage instances evaporate when the function ends. That shouldn't be the case. The Label widget should be holding a reference that keeps it alive, but if you store those PhotoImage objects in a list, as below, the code works:
def Hand(self):
self.but.destroy()
self.newCard = random.sample(self.cardsList, k=9)
self.keep = []
self.ext()
def download(self, url, ex, ey):
with urllib.request.urlopen(url) as u:
raw_data = u.read()
img = Image.open(BytesIO(raw_data)).resize((50,50),Image.ANTIALIAS)
iimage = ImageTk.PhotoImage(img)
Label(self.master, image=iimage).place(x=ex,y=ey)
self.keep.append(iimage)
I am trying to create a table with characters in Wxpython. Something of type:
┌─────────┬──────────┐
│columna1 │ columna2 │
├─────────┼──────────┤
│dato1 │ dato2 │
├─────────┼──────────┤
│dato3 │ dato4 │
└─────────┴──────────┘
I use the code dc.SetFont(wx.Font(12, wx.TELETYPE, wx.NORMAL, wx.NORMAL))
But monospaced seems to not apply to the lines in the table and therefore results in something similar to this:
┌─────────┬──────────┐
│columna1 │ columna2 │
├─────────┼──────────┤
│dato1 │ dato2 │
├─────────┼──────────┤
│dato3 │ dato4 │
└─────────┴──────────┘
I plan to apply the font to text that is going to be sent to a printer. Thank you.
This is an example code that has the error:
import wx
class TextDocPrintout(wx.Printout):
"""
A printout class that is able to print simple text documents.
Does not handle page numbers or titles, and it assumes that no
lines are longer than what will fit within the page width. Those
features are left as an exercise for the reader. ;-)
"""
def __init__(self):#, text, title, margins):
wx.Printout.__init__(self)#, title)
def HasPage(self, page):
return page <= self.numPages
def GetPageInfo(self):
return (1, self.numPages, 1, self.numPages)
def CalculateScale(self, dc):
# Scale the DC such that the printout is roughly the same as
# the screen scaling.
ppiPrinterX, ppiPrinterY = self.GetPPIPrinter()
ppiScreenX, ppiScreenY = self.GetPPIScreen()
logScale = float(ppiPrinterX)/float(ppiScreenX)
# Now adjust if the real page size is reduced (such as when
# drawing on a scaled wx.MemoryDC in the Print Preview.) If
# page width == DC width then nothing changes, otherwise we
# scale down for the DC.
pw, ph = self.GetPageSizePixels()
dw, dh = dc.GetSize()
scale = logScale * float(dw)/float(pw)
# Set the DC's scale.
dc.SetUserScale(scale, scale)
# Find the logical units per millimeter (for calculating the
# margins)
self.numPages = 1
self.logUnitsMM = float(ppiPrinterX)/(logScale*25.4)
def OnPreparePrinting(self):
# calculate the number of pages
dc = self.GetDC()
self.CalculateScale(dc)
def OnPrintPage(self, page):
dc = self.GetDC()
dc.SetFont(wx.Font(12, wx.TELETYPE, wx.NORMAL, wx.NORMAL))
texto = "┌─────────┬──────────┐\n"
texto += "│columna1 │ columna2 │\n"
texto += "├─────────┼──────────┤\n"
texto += "│dato1 │ dato2 │\n"
texto += "├─────────┼──────────┤\n"
texto += "│dato3 │ dato4 │\n"
texto += "└─────────┴──────────┘"
dc.DrawText(texto, self.logUnitsMM*15, self.logUnitsMM*15)
return True
class PrintFrameworkSample(wx.Frame):
def __init__(self):
wx.Frame.__init__(self)
# initialize the print data and set some default values
self.pdata = wx.PrintData()
self.pdata.SetPaperId(wx.PAPER_A4)
self.pdata.SetOrientation(wx.PORTRAIT)
def OnPrint(self):#, evt):
data = wx.PrintDialogData(self.pdata)
printer = wx.Printer(data)
printout = TextDocPrintout()
useSetupDialog = True
if not printer.Print(self, printout, useSetupDialog) and printer.GetLastError() == wx.PRINTER_ERROR:
wx.MessageBox(
"Hubo un problema al imprimir.\n"
"Su impresora está configurada correctamente?",
"Error al Imprimir", wx.OK)
else:
data = printer.GetPrintDialogData()
self.pdata = wx.PrintData(data.GetPrintData()) # force a copy
printout.Destroy()
app=wx.App(False)
PrintFrameworkSample().OnPrint()
app.MainLoop()
Specifying the font facename can force the issue:
dc.SetFont(wx.Font(12, wx.FONTFAMILY_TELETYPE, wx.NORMAL, wx.NORMAL, faceName="Monospace"))
However there is a FontEnumerator available, which can be used to select a suitable font from those available.
Here is an example of its use, looking for fixed width fonts.
import wx
class MyPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, -1)
fonts = wx.FontEnumerator()
fonts.EnumerateFacenames(wx.FONTENCODING_SYSTEM,fixedWidthOnly=True)
font_list = fonts.GetFacenames(wx.FONTENCODING_SYSTEM,fixedWidthOnly=True)
list_text = wx.StaticText(self, -1, "Face names:")
self.font = wx.ListBox(self, -1, size=(200, 500), choices=font_list)
self.font_size = wx.SpinCtrl(self, wx.ID_ANY, min=6, max=50, initial=16)
self.sample = wx.StaticText(self, -1, "Sample ")
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(list_text, 0, wx.ALL, 5)
sizer.Add(self.font, 0, wx.ALL, 5)
sizer.Add(self.font_size, 0, wx.ALL, 5)
sizer.Add(self.sample, 0, wx.ALL, 5)
self.SetSizer(sizer)
self.Layout()
self.font.Bind(wx.EVT_LISTBOX, self.OnSelect)
self.font_size.Bind(wx.EVT_SPINCTRL, self.OnSelect)
self.font.SetSelection(0)
self.font_size.SetToolTip('Select font size')
self.OnSelect(None)
def OnSelect(self, evt):
facename = self.font.GetStringSelection()
size = self.font_size.GetValue()
font = wx.Font(size, family=wx.DEFAULT, style=wx.NORMAL, weight=wx.NORMAL, underline=False, faceName=facename)
self.sample.SetLabel(facename)
self.sample.SetFont(font)
self.Refresh()
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None,title="Fixed Width FontEnumerator", size=(800,600))
panel = MyPanel(self)
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm()
frame.Show()
app.MainLoop()
Have you tried doing it using the triple quote? Please, try this and tell me:
texto = '''
┌─────────┬──────────┐
│columna1 │ columna2 │
├─────────┼──────────┤
│dato1 │ dato2 │
├─────────┼──────────┤
│dato3 │ dato4 │
└─────────┴──────────┘
'''
print(texto)
Good luck!
So I am trying to make a desktop-like interface in python with Tkinter, and I am trying to set the wallpaper but I have no idea how to resize it. Here is the code:
from tkinter import *
import tkinter.messagebox as box
import webbrowser
from PIL import Image, ImageTk
window=Tk()
window.title('Label Example')
window.configure(background = 'gray44')
#---=Main_Frame=---#
main_frame = Frame(window)
main_frame.pack(padx = 600, pady=350)
#---=Wallpaper=---#
img_wallpaper = ImageTk.PhotoImage(Image.open('minecraft main picture.gif').resize(10, 10)) # the one-liner I used in my app
label_w = Label(window, image=img_wallpaper)
label_w.image = img_wallpaper # this feels redundant but the image didn't show up without it in my app
label_w.pack()
##wallpaper_image = PhotoImage(file = 'minecraft main picture.gif')
##wallpaper = Label(window, image= wallpaper_image, width=400, height = 400)
##wallpaper_image_big = PhotoImage.subsample(wallpaper_image, x=1, y=1)
##can_wallpaper = \
##Canvas(window, width = 1200, height = 700)
##can_wallpaper.create_image((100, 100), image = wallpaper_image)
##can_wallpaper.place(x=0, y =0)
window.mainloop() #Main loop
I have tried used someone else's code to resize it with PIL pillow but it does not work.
Here is the error:
Traceback (most recent call last):
File "/Users/edwardandreilucaciu/Desktop/Desktop Interface Project/Desktop Interface.py", line 16, in <module>
img_wallpaper = ImageTk.PhotoImage(Image.open('minecraft main picture.gif').resize(10, 10)) # the one-liner I used in my app
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PIL/Image.py", line 1865, in resize
message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1]
ValueError: Unknown resampling filter (10). Use Image.NEAREST (0), Image.LANCZOS (1), Image.BILINEAR (2), Image.BICUBIC (3), Image.BOX (4) or Image.HAMMING (5)
Question: how to resize images in Tkinter
import kinter as tk
from PIL import Image, ImageTk
class ImageLabel(tk.Label):
def __init__(self, parent, **kwargs):
path = kwargs.pop('path', None)
if path is not None:
image = Image.open(path)
resize = kwargs.pop('resize', None)
if resize is not None:
image = image.resize(resize, Image.LANCZOS)
# Keep a reference to prevent garbage collection
self.photo = ImageTk.PhotoImage(image)
kwargs['image'] = self.photo
super().__init__(parent, **kwargs)
Usage:
class App(tk.Tk):
def __init__(self):
super().__init__()
lab=ImageLabel(self,
path="minecraft main picture.gif",
resize=(400, 400))
lab.grid()
if __name__ == '__main__':
App().mainloop()
It's actually quite easy
img_wallpaper = ImageTk.PhotoImage(Image.open('minecraft main picture.gif').resize(10, 10))
you see .resize is not availble for ImageTk image object also .resize takes a tuple of width and height
Try this
img_wallpaper = Image.open('minecraft main picture.gif').resize((10,10))
img_wallpaper = ImageTk.PhotoImage(img_wallpaper)