Stop frames from resizing in respect to the content (Tkinter + Python2.7) - python-2.7

I am trying to make something like this using frames:
And this is my code so far: # I am trying to put the frames in the certain location only, and not fill the entire display
from Tkinter import *
class Menu():
def display(self):
self.canvas = Canvas(width=1200,height=700)
self.canvas.grid()
self.controlcanvas = Canvas(self.canvas,width=850,height=200)
self.controlcanvas.place(x=348,y=107)
indexframe = Frame(self.controlcanvas)
titleframe = Frame(self.controlcanvas)
readCframe = Frame(self.controlcanvas)
commentCframe = Frame(self.controlcanvas)
indexframe.pack(side=LEFT)
titleframe.pack(side=LEFT)
readCframe.pack(side=LEFT)
commentCframe.pack(side=LEFT)
dummyindex = Label(indexframe,text="#").grid(row=0,column=0)
dummytitle = Label(titleframe,text="Title").grid(row=0,column=1)
dummyreadC = Label(readCframe,text="Read Count").grid(row=0,column=2)
dummycommentC = Label(commentCframe,text="Comments").grid(row=0,column=3)
mainloop()
m = Menu()
m.display()
The problem here is that the # Title Read Count and Comments resize the frame into small one.
I want the frames to retain their original geometry so that I could create something like the picture.
Any help?

Frame has a list of config options that handle its properties like size and border. When you create the frame, you can specify these options:
indexframe = Frame(self.controlcanvas, height=400, width=200, borderwidth=2)
or you can access them later via:
indexframe.config(borderwidth=2)
Take a look at the method documentation for more options.

Related

Embedding StackView to MaterialSwift Card Content

I am attempting to use the CardTableView, and I am able to render cards from my API call. However, I am trying to load multiple UILabels and lay them out using UIStackViews within the content area of the card. The toolbar and bottom bar already have icons and will be used appropriately.
When I embed the stackView and dont set translatesAutoresizingMaskIntoConstraints = false the cards are spaced correctly, as shown in this picture:
However there is none of my labels visible. The following picture shows that when i set translatesAutoresizingMaskIntoConstraints = false the labels show up, but the card spacing is all ruined.
Here is my method for preparing the Content:
private func prepareCardContent() {
contentLabelStackView = UIStackView()
contentLabelStackView.axis = UILayoutConstraintAxis.vertical
contentLabelStackView.distribution = UIStackViewDistribution.equalSpacing
contentLabelStackView.alignment = UIStackViewAlignment.leading
contentLabelStackView.spacing = 0
contentLabelStackView.addArrangedSubview(invitedLabel)
contentLabelStackView.addArrangedSubview(teeUpTitle)
contentLabelStackView.translatesAutoresizingMaskIntoConstraints = false
}
And this is my code for preparing the card itself:
private func preparePresenterCard() {
card.toolbar = toolbar
card.contentView = contentLabelStackView
card.contentViewEdgeInsetsPreset = .vertically5
card.bottomBar = bottomBar
card.depthPreset = .depth3
contentView.addSubview(card)
}
I am unsure what is conflicting with the spacing and layout of the cards with using a nested StackView.
Set a height value to the UIStackView :)

Tkinter Background not showing transparent

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)

Wanting to get an output and run a programme together with Tkinter

What I want to be able to do is run a list of MIDI files, I have the programme to list them out and play them...
import os,fnmatch,pygame
pygame.mixer.init()
List = []
Song = 0
def Update():
List = []
for file in os.listdir('.'):
if fnmatch.fnmatch(file, '*.mid'):
List.append(file)
return List
List = Update()
while True:
while Song <= len(List):
pygame.mixer.music.load(List[Song])
pygame.mixer.music.play(1)
while pygame.mixer.music.get_busy() == True:
List = Update()
Song = Song + 1
Song = 0
This currently works with .mid files that it is in the same folder as, however I want to implement a slider with the programme to control the volume, I also have that code already...
from Tkinter import *
master = Tk()
def getThrottle(event):
Volume = Throttle.get()
Throttle = Scale(master, from_=0, to=100, tickinterval=10, length=200, orient=HORIZONTAL, command=getThrottle)
Throttle.set(0)
Throttle.pack()
mainloop()
What I want to know is how I can make both programmes run at the same time with a single variable global between both with that variable being Volume
Nevermind, I discovered how to run both a tkinter window and music at the same time, however a new problem is that the tkinter window is blank.
New question is "Why is the tkinter window blank?"

Tabbed GUI keeps hanging on entry box

I have a very primitive GUI built with Tkinter. This is my first attempt at a GUI so I am struggling to understand what is going on (and with syntax). Here is what I have:
from __future__ import division, print_function
import os, ttk, tkFileDialog, Tkconstants
import Tkinter as tk
import datetime as dt
Tkinter = tk
# define OS version
version = '0.0.2'
class TestGUI(tk.Tk):
def __init__(self,parent):
tk.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
# try building list of instruments and sites
if os.path.isfile('config'):
with open(''config','r') as config:
config = dict( [(r.split('=')[0].strip(), r.split('=')[1].strip()) for r in config.read().split('\n') if r[0]<>'#'] )
self.datapath = config['datapath']
else:
self.datapath = '../'
def initialize(self):
self.grid()
# set up tabs
self.geometry( "%dx%d+%d+%d" % (1500, 900, 200, 50) )
nb = ttk.Notebook(self)
nb.pack(fill='both',expand='yes')
f1 = tk.Frame(bg='green')
f2 = tk.Frame(bg='blue')
f3 = tk.Frame(bg='red')
f1.grid()
f2.grid()
f3.grid()
nb.add(f1, text='General'.ljust(12,' '))
nb.add(f2, text='Plot'.ljust(12,' '))
nb.add(f3, text='Analysis'.ljust(12,' '))
button = tk.Button(f2,text='I AM A BUTTON!')
button.pack(side='left', anchor='nw', padx=3, pady=5)
# insert button and text box for specifying data location
path_button = tk.Button(f1,text='Browse',command=self.askdirectory).pack(side='left', anchor='nw', padx=10, pady=15)
self.path_entry = tk.StringVar()
self.entry = tk.Entry(f1,textvariable=self.path_entry)
self.entry.grid(column=12,row=8,columnspan=10)
self.entry.bind("<Return>", self.OnPressEnter)
self.path_entry.set(u"Sites directory path...")
def OnButtonClick(self):
print("You clicked the button !")
def OnPressEnter(self,event):
print("You pressed enter !")
def askdirectory(self):
"""Returns a selected directoryname."""
self.datapath = tkFileDialog.askdirectory()
self.path_entry.set(self.datapath)
if __name__ == "__main__":
app = TestGUI(None)
app.title(version)
app.mainloop()
My problem is centered around the addition of an entry box here:
self.path_entry = tk.StringVar()
self.entry = tk.Entry(f1,textvariable=self.path_entry)
self.entry.grid(column=12,row=8,columnspan=10)
self.entry.bind("<Return>", self.OnPressEnter)
self.path_entry.set(u"Sites directory path...")
If I run the code as-is, it just hangs (it also hangs if I use "f2"; I suspect it is getting caught in the infinite loop without actually doing anything). However, if I change the parent from "f1" to "f3" or it works (the entry box is now in frame 3 instead of frame 1, but it at least does not hang on me). There is another issue even when f3 is used: the entry box's width/position never change despite my changing of column/row/columnspan values.
Does anyone know why the code is hanging when I specify "f1" or "f2" and how to fix it?
Does anyone know why my entry box position/size is not changing?
You have put widgets in f1 and f2 using the pack geometry manager:
button = tk.Button(f2,text='I AM A BUTTON!')
button.pack(side='left', anchor='nw', padx=3, pady=5)
#and
path_button = tk.Button(f1,text='Browse',command=self.askdirectory).pack(side='left', anchor='nw', padx=10, pady=15)
Mixing geometry managers can lead to your program hanging, so using grid to put in the Entry does exactly that.
From effbot.org:
Warning: Never mix grid and pack in the same master window. Tkinter will happily spend the rest of your lifetime trying to negotiate a solution that both managers are happy with. Instead of waiting, kill the application, and take another look at your code. A common mistake is to use the wrong parent for some of the widgets.
The problem you describe of the Entry not changing position is because it is the only widget there, so the row(s) and column(s) in which the entry is are the only ones which do not have a width and height of 0. To make rows and columns without widgets take up space, use grid_rowconfigure(index, weight=x) where x is non-zero. An example is given in this answer.
Again from effbot.org:
weight=
A relative weight used to distribute additional space between rows. A row with the weight 2 will grow twice as fast as a row with weight 1. The default is 0, which means that the row will not grow at all.

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