Below is my code. The code is from within a different program, so a button would be clicked
on another program and initiate this code.I have been struggling with this a while, in short i am trying to a) take an image, save it to a directory, b) display the image on canvas or root a long with a button named "refresh". When refresh is clicked then remove is called deleting the 'file' first taken, takes another picture and refreshes the canvas with the second picture taken and so on and on. I am not seeming to get it to work in this sequence and have used multiple examples etc etc. Can anyone assist please, is my design incorrect perhaps? I have ample other code but the code below details only one function calling global properties etc etc. I would appreciate an answer but also want to learn from the answer to understand what is being done wrong.
import os
import sys
import time
from VideoCapture import Device
impot Image
from PIL import ImageTk, Image
from Tkinter import *
import Tkinter
root = Tk()
root.wm_title("Camera Capture")
root.resizable(0,0)
root.geometry("600x400")
path = ('C:\Users\Public')
os.chdir(path)
def take_picture():
global root
global path
os.chdir(path)
cam = Device()
cam.saveSnapshot('pic.gif')
webcam_pic = Tkinter.PhotoImage(file='./pic.gif')
item = Label(root, anchor = W, image = webcam_pic)
item.pack()
button_take_picture = Button(root, text = "Take picture", command = take_picture(), bg
= 'blue')
button_take_picture.place(relx = .9, rely = .5, anchor = "center")
mainloop()
actually the command should be without this '()'
command =take_picture
button_take_picture = Button(root, text = "Take picture", command = take_picture, bg=blue')
Related
from PIL import Image
from tkinter import filedialog as fd
import os
import ctypes
import tkinter
class ImageList:
path = ""
dir = ""
top = tkinter.Tk()
canvas = tkinter.Canvas()
canvas.pack()
def __init__(self):
self.path = os.path.expanduser('~/')
def findImage(self):
image = Image.open(self.dir, "rb")
image.show()
def fileExplorer(self, path):
self.canvas.destroy()
self.canvas = tkinter.Canvas()
self.canvas.pack()
obj = os.scandir(path)
for entry in obj:
if entry.is_dir():
#self.path = os.path.abspath(self.path)
b = tkinter.Button(self.canvas, text=entry.name, command=lambda: self.fileExplorer(os.path.abspath(entry).replace('//', '\\')))
b.pack()
elif entry.is_file():
b = tkinter.Button(self.canvas, text=entry.name, command=lambda: print(entry.name))
b.pack()
else:
obj.close()
self.top.mainloop()
As shown in the code above, I am trying to make exe that shows the subdirs and files after C:\Users using buttons in tkinter and repeating it by using recursion.
The first error is that in "os.path.abspath(entry).replace('//', '\')" shows path in a format of "C://Users" and I intended to change that to "C:\Users" using the replace method. However, using "\" doesn't replace "//" and still shows as the original format.
The second error is that after running the code, when I press any button it acts as if I pressed the last button in the tkinter window, meaning that it recursively called the last subdir or the file below "C:\Users".
I'm just getting used to python and this is my first time using stackoverflow. I'm sorry if I did not abide by any of the rules in stackoverflow. Thanks for anyone helping.
I've been looking around for this but all the solutions feel extremely complex and even then I haven't been able to get it to work how I want it. I'm making a program that randomly opens an image from a folder, waits 10 seconds, then opens another random image from the same folder, and keeps going.
Simple enough, I was able to do it in a While True loop and making the "wait 10 seconds" part with time.sleep(10). But, I'd like to have a button that simply resets it whenever I feel like it. I'm doing this in tkinter and I have a button that starts it, but when I added a button to reset it, I haven't been able to click it and when I try to, the program crashes. That's because it's in the time.sleep(10) and the whole program stops for 10 seconds. For anyone curious about the code, here it is.
from tkinter import *
import random
import os
from PIL import Image
import time
root = Tk()
def AnmuViewer():
while True:
random_pic = (random.choice(os.listdir("D:/de_clutter/memez/anmu")))
openPic = Image.open('D:/de_clutter/memez/anmu/' + random_pic)
openPic.show()
time.sleep(10)
continue
def Restart():
AnmuViewer()
start_btn = Button(root, text = "Start", command = AnmuViewer)
start_btn.pack()
next_btn = Button(root, text = 'Restart', command = Restart)
next_btn.pack()
root.mainloop()
I know I don't need a "Restart" button as being able to click the "Start" button again would've done the same thing. Either way, that "Start" button itself is also unclickable.
I've looked into threading so I'm thinking of making a function that counts down from 10, and when it reaches 10, the AnmuViewer() starts over again, that way I can click "Start" again whenever and reset the whole code from scratch. But I just haven't been able to get that to work either. Any suggestions?
You can combine start and reset in the same button, but you can also add a reset button that calls the same function (commented code).
That is upon start, the system is reset to its initial state, here with the callback value set to None.
Most times, it is better to use tkinter.mainloop than a custom while loop. Using time.sleep in GUIs is usually a recipe for disaster as it blocks all interactivity during its execution.
I replaced the images with a text label for simplicity, you will have to change that.
import tkinter as tk
import random
def anmu_viewer():
global cb
random_pic = random.choice(images)
lbl.config(text=random_pic)
cb = root.after(10000, anmu_viewer) # keep a reference of the callback
def reset():
global cb
if cb is not None:
root.after_cancel(cb) # cancel the callback
cb = None # reset the reference to the callback to None
anmu_viewer()
images = ['im1', 'im2', 'im3', 'im4', 'im5', 'im6']
root = tk.Tk()
cb = None
lbl = tk.Label(root, text='')
lbl.pack()
start_btn = tk.Button(root, text="Start", command=reset)
start_btn.pack()
# reset_btn = tk.Button(root, text="Reset", command=reset)
# reset_btn.pack()
root.mainloop()
Using while with tkinter will cause some issues with mainloop() and will freeze the issue. You should be using after(ms,func) which does not freeze the GUI. A very simple code can do this, take a look here:
from tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image
from glob import glob #for the path of the image
import random
root = Tk()
def anmuViewer():
global cb
choice = random.choice(all_img) #random choice of image from the list of img
cur = ImageTk.PhotoImage(file=choice) #make an image object
img_label.config(image=cur) #changing the image on the label
img_label.img = cur #keeping a reference to the image
cb = root.after(10000,anmuViewer) #repeating the function every 10 second
def restart(): #reset func from Roblochons code
global cb
if cb is not None:
root.after_cancel(cb)
cb = None
anmuViewer()
path = filedialog.askdirectory(title='Choose the directory with images') #ask the directory with the image.
png = glob(path+'/*.png') #pick all the png image
jpg = glob(path+'/*.jpg') #pick all the jpg image
all_img = png + jpg #concatenate both the list
img_label = Label(root) #image label, later to be configured
img_label.pack()
start_btn = Button(root, text = "Start", command=anmuViewer)
start_btn.pack(padx=10,pady=10)
next_btn = Button(root, text = 'Restart', command=restart)
next_btn.pack(padx=10,pady=10)
root.mainloop()
I've explained the code with comments so its easier to understand on the go. I've not assumed what path of image you have, so I'm choosing the paths dynamically as you can see. The code looks long, because I simplified most lines of code to understand better.
Anyway you will need to resize the image so that it fits the screen for everyone, because pixels and screen resolution varies from device. Take a look here
I am new to GUI programming and recently started working with tKinter.
My problem is that the program won't show my image, I'm suspecing that it is my code that is wrong, however, I would like somone to exactly explain to me how i can make it work...
Here's my code:
from tkinter import * # Import the tkinter module (For the Graphical User Interface)
from PIL import ImageTk, Image
width = 1920
height = 1080
RootGeo = str(width) + "x" + str(height) # Make a def for RootGeo so the Root geometry isn't hardcoded
def MakeWindow():
# -----Root_Attributes-----
Root = Tk()
Root.geometry(RootGeo)
Root.state("zoomed")
# -----Root_Attributes, Root_Containers----- ### NOT WORKING ###
__DISPlAY__ = Image.open("Display.png")
__DISPLAY_RENDER__ = ImageTk.PhotoImage(__DISPlAY__)
Display_icon = Label(Root, image=__DISPLAY_RENDER__)
Display_icon.image = __DISPLAY_RENDER__
Display_icon.place(x=0, y=0)
# -----Root_Containers----- ### NOT WORKING ###
Root.mainloop()
MakeWindow()
Any and all help would be very appreciated.
try to change the image and check out if its still not showing up.
if its still not showing up, try to change this line:
__DISPlAY__ = Image.open("Display.png")
to
__DISPlAY__ = Image.open("Display.png").resize((600,800))
see if it would show up now then change the width and height as you like.
Pychamarm does not want to show the images, so to solve this problem i had to run the script from cmd every time...
I'm still quiet new to programming, so maybe my question in pretty easy or even stupid. As said in the title I'm trying to programm a for loop, which creates a pictured button widget for each picuture in a certain folder. This is what I have so far:
import tkinter
from tkinter import ttk
from tkinter import PhotoImage
import os
root = tkinter.Tk()
list_files = os.listdir(".")
for file in list_files:
if file.endswith(".gif"):
drink = PhotoImage(file)
print(drink)
b1 = ttk.Button(image=drink, text="Hello", compound="right").pack()
l1 = ttk.Label(image=drink).pack()
root.mainloop()
Now what I get is two widgets, one label displaying nothing and a button displaying Hello. In the shell it says drink1.gif, which is correct, because that's the only gif file in my standard python folder...
what have I done wrong?
Use PhotoImage(file='path_to_file') to create image from path.
When PhotoImage object is garbage-collected by Python, the label is cleared. You must save reference to drink object somewhere: l1.image = drink:
http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm
widget.pack() method return nothing.
import tkinter
from tkinter import ttk
from tkinter import PhotoImage
import os
root = tkinter.Tk()
list_files = os.listdir(".")
for path in list_files:
if path.endswith(".gif"):
drink = PhotoImage(file=path)
b1 = ttk.Button(root, image=drink, text="Hello", compound="right")
b1.pack()
l1 = ttk.Label(root, image=drink)
l1.image = drink
l1.pack()
root.mainloop()
PhotoImage(file) creates an image and gives it the name "drink1.gif", which is returned. If you actually want to load the file into the image, you need PhotoImage(file = file).
I believe you are supposed to run self.pack, according to the Zetcode tutorial.
I'm building a small educational app.
I already have all the code done, all I'm missing is a way is getting a window to open with TK displaying a textbox, an image and a button.
All it should do, it return the text inserted in the textbox after clicking the button and closing the windows.
So, how do I do this?
I have been looking at code, but nothing I did worked, I almost fell ashamed being this so basic.
Thanks
An easy way to write GUIs is using Tkinter. There's an example that display a windows with a text and a button:
from Tkinter import*
class GUI:
def __init__(self,v):
self.entry = Entry(v)
self.entry.pack()
self.button=Button(v, text="Press the button",command=self.pressButton)
self.button.pack()
self.t = StringVar()
self.t.set("You wrote: ")
self.label=Label(v, textvariable=self.t)
self.label.pack()
self.n = 0
def pressButton(self):
text = self.entry.get()
self.t.set("You wrote: "+text)
w=Tk()
gui=GUI(w)
w.mainloop()
You may look at the Tkinter documentation, the label widget also supports to include pictures.
Regards
This is a simple code that get the input from the inputBox to myText. It should get you started on the right direction. Depending on what else you need to check or do, you can add more functions to it. Notice you might have to play around with the order of the line image = tk.PhotoImage(data=b64_data). Because if you put it right after b64_data = .... It will gives you error. (I am running MAC 10.6 with Python 3.2). And the picture only works with GIF at the moment. See reference at the bottom if you want to learn more.
import tkinter as tk
import urllib.request
import base64
# Download the image using urllib
URL = "http://www.contentmanagement365.com/Content/Exhibition6/Files/369a0147-0853-4bb0-85ff-c1beda37c3db/apple_logo_50x50.gif"
u = urllib.request.urlopen(URL)
raw_data = u.read()
u.close()
b64_data = base64.encodestring(raw_data)
# The string you want to returned is somewhere outside
myText = 'empty'
def getText():
global myText
# You can perform check on some condition if you want to
# If it is okay, then store the value, and exist
myText = inputBox.get()
print('User Entered:', myText)
root.destroy()
root = tk.Tk()
# Just a simple title
simpleTitle = tk.Label(root)
simpleTitle['text'] = 'Please enter your input here'
simpleTitle.pack()
# The image (but in the label widget)
image = tk.PhotoImage(data=b64_data)
imageLabel = tk.Label(image=image)
imageLabel.pack()
# The entry box widget
inputBox = tk.Entry(root)
inputBox.pack()
# The button widget
button = tk.Button(root, text='Submit', command=getText)
button.pack()
tk.mainloop()
Here is the reference if you want to know more about the Tkinter Entry Widget: http://effbot.org/tkinterbook/entry.htm
Reference on how to get the image: Stackoverflow Question