Tkinter Background not showing transparent - python-2.7

Hey im a newbie in python in my code there is a animated gif that play whenever i run the code. The gif image is actually transparent when open in adobe etc. but the problem is when i run the code.The frame which is the color gray included in the gif.I want to remove the color gray so that the only thing that can see is my only animated gif
This is my code:
# mimic an animated GIF displaying a series of GIFs
# an animated GIF was used to create the series of GIFs
# with a common GIF animator utility
import time
from Tkinter import *
root = Tk()
imagelist = ["dog001.gif","dog002.gif","dog003.gif"]
# extract width and height info
photo = PhotoImage(file=imagelist[0])
width = photo.width()
height = photo.height()
canvas = Canvas(width=width, height=height)
canvas.create_line(0,240,640,240, fill='blue')
canvas.pack()
# create a list of image objects
giflist = []
for imagefile in imagelist:
photo = PhotoImage(file=imagefile)
giflist.append(photo)
# loop through the gif image objects for a while
for k in range(0, 10):
for gif in giflist:
canvas.delete(ALL)
canvas.create_image(width/2.0, height/2.0, image=gif)
canvas.update()
time.sleep(0.1)
root.mainloop()[![enter image description here][1]][1]
dog001.gif
dog002.gif
dog003.gif

As described here, making a Tkinter window transparent is possible, but depends on your OS.
If you are on Windows, just add the following lines after creating the root:
root = Tk()
# Hide the root window drag bar and close button
root.overrideredirect(True)
# Make the root window always on top
root.wm_attributes("-topmost", True)
# Define a transparent color
root.wm_attributes("-transparentcolor", '#eeefff')
Then set your canvas' background color as the transparent color defined above:
canvas = Canvas(width=width, height=height, bg='#eeefff', highlightthickness=0)

Related

How to replace previous image with new image in QGrapicsScene

In Constructor, using QGraphicScene I'm adding many widgets and one image using Qpixmap. when I want to replace only image. i'm able replace the image but these widgets are not coming ..`
QPixmap *bkgnd=new QPixmap(":/res/Clamp Down - Pedistal Down - Arm Retracted - Complete.jpg");
m_bkImgScene.addPixmap(*bkgnd);
m_bkImgScene.addItem(&m_txtForelinePsr);
m_txtForelinePsr.setPos(POS_FORELINEPSR);
m_bkImgScene.addItem(&m_txtMechPump);
m_txtMechPump.setPos(POS_MECHPUMP);
m_bkImgScene.addItem(&m_txtRoughLnPsr);
m_txtRoughLnPsr.setPos(POS_ROUGHLINEPSR);
m_bkImgScene.addItem(&m_txtHeBartn);
m_bkImgScene.addItem(&m_txtHeMfc);
m_bkImgScene.addItem(&m_txtIonGfb);
m_bkImgScene.addItem(&m_txtProBaratronfb);
m_txtProBaratronfb.setPos(POS_PROBARATRONFB);
m_bkImgScene.addItem(&m_txtChamberPsr);
m_mapTxtWxs[CHAMBERPRESSUREFEEDBACK] = &m_txtChamberPsr;
m_txtChamberPsr.setPos(POS_CHAMBERPSR);`
mypixmap->load("secondimage_path");
mylabel->setPixmap(mypixmap);

put label in frame without class etc

How can I get the label in this simple frame? I tried to make the label go to the frame but then I only see the label and the frame disappears.
Notice here that I want 2 different sizes. The root.geometry("200x200") which is gray. I also am putting a Frame in the root of 100w x 100h. Run the code, I can see both color areas great. But my label does not appear, in the Frame darkgray area. Which is my problem.
from Tkinter import *
root=Tk()
root.geometry("200x200")
root.title("basicGUI")
root.configure(background="gray")
frame = Frame(width=100, height=100,
bg="darkgray")
frame.pack()
mylabel=Label(text="anyWord")
mylabel.pack()
"""
# darkgray frame disappears
mylabel=Label(frame, text="anyWord")
mylabel.pack(side = LEFT)
"""
mainloop()
Thanks to Lafexlos, a one line addition solved my problem.
from Tkinter import *
root=Tk()
root.geometry("200x200")
root.title("basicGUI")
root.configure(background="gray")
frame = Frame(width=100, height=100,
bg="darkgray")
frame.pack_propagate(0) #adding line solves problem
frame.pack()
mylabel1=Label(frame, text="anyWord")
mylabel1.pack(side = TOP)
mainloop()

Cannot dynamically change font in python Tkinter text editor

Recently I have been working on a GUI python plain text editor. The code calls this function:
def TimesNewRoman():
global fontname
global font
fontname = "Times New Roman"
print font
The variables are:
fontname = "Calibri"
size = "14"
font = fontname + " " + size
And Tkinter reads the font with the code:
textPad.config(
borderwidth=0,
font=font ,
foreground="green",
background="black",
insertbackground="white", # cursor
selectforeground="blue", # selection
selectbackground="#008000",
wrap="word",
width=64,
undo=True, # Tk 8.4
)
However, I cannot get it to work. I get no errors but the font remains Calibri. I have searched the internet looking for anything that might allow me to dynamically change the font of the text canvas, but I have not succeeded in finding one that works. Any help in implementing a font modifying feature would be very much appreciated.
I am using python 2.7.7, Tkinter, and I am running this on Windows 7.
Your function should change the font name to "Times New Roman". Are you sure you are calling the function?
Just for completeness, as also Bryan Oakley stated, you should use the tuple syntax when specifying a font name with more than one word (like I am doing in the example below).
If it's ok to dynamically change the font of the Text widget with the click of a button, then the following could be a simple solution that uses a Toplevel widget to let the user write the font and size:
import Tkinter as tk
def choose_font():
global m, text # I hate to use global, but for simplicity
t = tk.Toplevel(m)
font_name = tk.Label(t, text='Font Name: ')
font_name.grid(row=0, column=0, sticky='nsew')
enter_font = tk.Entry(t)
enter_font.grid(row=0, column=1, sticky='nsew')
font_size = tk.Label(t, text='Font Size: ')
font_size.grid(row=1, column=0, sticky='nsew')
enter_size = tk.Entry(t)
enter_size.grid(row=1, column=1, sticky='nsew')
# associating a lambda with the call to text.config()
# to change the font of text (a Text widget reference)
ok_btn = tk.Button(t, text='Apply Changes',
command=lambda: text.config(font=(enter_font.get(),
enter_size.get())))
ok_btn.grid(row=2, column=1, sticky='nsew')
# just to make strechable widgets
# you don't strictly need this
for i in range(2):
t.grid_rowconfigure(i, weight=1)
t.grid_columnconfigure(i, weight=1)
t.grid_rowconfigure(2, weight=1)
m = tk.Tk()
text = tk.Text(m)
text.pack(expand=1, fill='both')
chooser = tk.Button(m, text='Choose Font', command=choose_font)
chooser.pack(side='bottom')
tk.mainloop()
When you click Choose Font, another window shows up, where you can insert the font name and the font size. You can apply the new font name and font size through the click of another Button Apply Changes, which uses a lambda.
Note that I have not handled any possible wrong inputs (for example inserting a letter for the size), you can do it by your own.
The problem is how you are specifying the font. You should use a tuple rather than a string. Try this:
font = (fontname, size)
textPad.config(
...,
font=font,
...
)
A good place for tkinter documentation is effbot.org. On the page about widget styling it says this about specifying the font:
Note that if the family name contains spaces, you must use the tuple
syntax described above.

pygame my picture wont show up on my window

import pygame
import sys
import os
from pygame.locals import *
#Allows for the editing of a window
pygame.init()
#Sets screen size
window = pygame.display.set_mode((800,600),0,32)
#Names the window
pygame.display.set_caption("TEST")
#Types of colors (red,green,blue)
black = (0,0,0)
blue = (0,0,255)
green = (0,255,0)
yellow = (255,255,0)
red = (255,0,0)
purple = (255,0,255)
lightblue = (0,255,255)
white = (255,255,255)
pink = (255,125,125)
mif="climb.PNG"
mif=pygame.image.load(mif).convert()
#Loop
gameLoop = True
while gameLoop:
pygame.display.flip() #must flip the image o the color is visable
window.blit(mif, (0,0))
window.fill(black) #used to fill the creen with the certian color variables
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameLoop=False #Allows the user to exit the loop/game
pygame.quit() #quit the pygame interface
exit(0)
When I select run my yellow window pops up but no image...
I'm new to pygame and python so maybe I just did something wrong?
Is there a specific place that I should have my image saved to?
I'm running on a windows 8 hp ENVY...
I just want to learn what I'm doing wrong so I don't make the error again. (I should also add that I have tried many different pictures and some where not able to be located.)
First fill window with black color window.fill(black),
then put image on it window.blit(mif, (0,0)),
and last send it to your graphic card (and on your monitor) pygame.display.flip()
window.fill(black)
window.blit(mif, (0,0))
pygame.display.flip()
If your image is as big as window then you don't need to use fill(black).
You can keep image in the same folder with script. Or you can create subfolder only for image to have order in folders.
If you call this folder images then you have to add this to filenames images/climb.PNG.
BTW: better use / than \ in path because \n in path can be interpreted as ENTER/new line as in any text.
But the most properly is:
import os
filename = os.path.join('images', 'climb.PNG')

Fish swim in pygame

I want to use the python pygame module to make a 2D "fishtank".
Basically I will load a jpg image as background and load a gif animated image depicting fish swimming and make it move.
I know how to make an static image move but how to make a gif image move while the image itself is animated.
I have PIL installed, do sure if need to use it.
If that does not work, I can also break apart the gif file into several static frames and cyclically make each of them show on screen. When the latter one is posted, the former one needs to be removed, how to remove it ?
Here is a class I used in my name to get PyGame animation to work:
class Animation(pygame.sprite.Sprite):
def __init__(self, img, fps = 6):
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
# Slice source image to array of images
self.images = self.loadSliced(img)
# Track the time we started, and the time between updates.
# Then we can figure out when we have to switch the image.
self._start = pygame.time.get_ticks()
self._delay = 1000 / fps
self._last_update = 0
self._frame = 0
self.image = self._images[self._frame]
def loadSliced(w, h, filename):
"""
Pre-conditions:
Master can be any height
Sprites frames must be the same width
Master width must be len(frames)*frames.width
Arguments:
w -- Width of a frame in pixels
h -- Height of a frame in pixels
filename -- Master image for animation
"""
images = []
if fileExists( img, "Animation Master Image"):
master_image = pygame.image.load(filename).convert_alpha()
master_width, master_height = master_image.get_size()
for i in range(int(master_width/w)):
images.append(master_image.subsurface((i*w, 0, w, h)))
return images
def update(self, t):
# Note that this doesn't work if it's been more than self._delay
# time between calls to update(); we only update the image once
# then. but it really should be updated twice
if t - self._last_update > self._delay:
self._frame += 1
if self._frame >= len(self._images):
self._frame = 0
self.image = self._images[self._frame]
self._last_update = t
self.image = self._images[self._frame]
self._last_update = t
def getFrame(self, screen):
# Update Frame and Display Sprite
self.update(pygame.time.get_ticks())
return self.image