from Tkinter import *
from PIL import Image, ImageTk
import os
class App:
def __init__(self,master):
master.minsize(width=666, height=666)
master["bg"] = "black"
self.button = Button(text="Camera1",command=self.playvid)
self.button.pack(side= "top")
self.img = ImageTk.PhotoImage(Image.open("car.png"))
self.panel = Label(master, image=self.img)
self.panel.pack(side = "bottom", fill = "both", expand = "yes")
def playvid(self):
os.system("gst-launch-1.0 videotestsrc ! autovideosink")
root = Tk()
app = App(root)
root.mainloop()
root.destroy()
This is my code. If I press the s key, I want to stop the os.system process that creates the gstreamer window, i.e. if I press s then it should be equivalent to ctrl + c.
Also is it possible to play the video in tkinter itself?
Related
when i run python file kill_app its run first 2nd python file(Hb_test.py) then run 1st python on tkinter.i am using vs code and python version is 3.10
see the code below
from tkinter import*
from Lab.Hb_Test import Hba
class kill_App:
def __init__(self,root):
self.root = root
self.root.geometry("1350x700+0+0")
self.root.title("Billing Software")
bg_color = "#074463"
title = Label(self.root,text = "PATHOLAB",bd=12,relief=GROOVE,bg=bg_color,fg="white",
font = ("ALGERIAN",40),pady=2).pack(fill=X)
if __name__=="__main__":
root =Tk()
obj = kill_App(root)
root.mainloop()
****
this is my second
**
**from tkinter import*
from tkinter import ttk
class Hba:
def __init__(self,root):
self.root = root
self.root.geometry("300x70+200+200")
self.root.title("JIBAN PRABHA PATHOLAB")
bg_color = "#074463"
Hb = LabelFrame(self.root,text="BLOOD TEST",font=("ALGERIAN",15,"bold")
,fg="gold",bg=bg_color)
Hb.place(x=0,y=0)
self.hb_neu_lbl = Label(Hb,text="Hb%(sahils) Test",bg=bg_color,fg="white",font=("Bell MT",15,"bold")).grid(row=1,column=1,padx=5,pady=5)
self.hb_neu=Entry(Hb,width=10,font="BellMT 15",bd=5,relief=SUNKEN).grid(row=1,column=2,padx=5,pady=5)
root = Tk()
obj = Hba(root)
root.mainloop()**
**
When Hb_Test is imported, its code will be executed, so the last three lines in the module will create a window:
Hb_Test.py
...
# below lines will create a window
root = Tk()
obj = Hba(root)
root.mainloop()
Note that it is not recommended to create more than one instance of Tk() and execute .mainloop() more than once.
For window other than the main/root window, use Toplevel instead of Tk. For your case, I would suggest that Hba inherits from Toplevel:
import tkinter as tk
class Hba(tk.Toplevel):
def __init__(self, master=None, **kwargs):
super().__init__(master, **kwargs)
self.geometry("300x70+200+200")
self.title("JIBAN PRABHA PATHOLAB")
bg_color = "#074463"
Hb = tk.LabelFrame(self, text="BLOOD TEST", font=("ALGERIAN",15,"bold"), fg="gold", bg=bg_color)
Hb.place(x=0, y=0)
self.hb_neu_lbl = tk.Label(Hb, text="Hb%(sahils) Test", bg=bg_color, fg="white", font=("Bell MT",15,"bold"))
self.hb_neu_lbl.grid(row=1,column=1,padx=5,pady=5)
self.hb_neu = tk.Entry(Hb, width=10, font="BellMT 15", bd=5, relief=tk.SUNKEN)
self.hb_neu.grid(row=1,column=2,padx=5,pady=5)
Note that I have changed from tkinter import * to import tkinter as tk because wildcard import is not recommended as well.
Also don't write code like below:
self.hb_neu_lbl = Label(Hb,text="Hb%(sahils) Test",bg=bg_color,fg="white",font=("Bell MT",15,"bold")).grid(row=1,column=1,padx=5,pady=5)
because self.hb_neu_lbl will be None (result of .grid(...)). Code like below instead:
self.hb_neu_lbl = Label(Hb, text="Hb%(sahils) Test", bg=bg_color, fg="white", font=("Bell MT",15,"bold"))
self.hb_neu_lbl.grid(row=1,column=1,padx=5,pady=5)
I have a gui in python3 that I want to call another python script using subprocess (or something better?). I have the main gui full screen, which is what I want. The problem is, when I launch the subprocess, it initially becomes the topmost window on LXDE, so far so good. You can click on the main gui in the background which brings the main gui to topmost. This is what is expected from the window manager, but this covers the subprocess that I currently have blocking the main gui. I need to prevent the main gui from accepting focus while the subprocess is running or keeping the subprocess as topmost window.
maingui.py
#!/usr/bin/env python3
import tkinter as tk
import subprocess
def on_escape(event=None):
print("escaped")
root.destroy()
def do_something():
child = subprocess.run(["python3", "childgui.py"], shell=False)
######################################################################
busy=False
root = tk.Tk()
root.title("My GUI")
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
#don't run this as the subprocess blocks #root.attributes("-fullscreen", True) # run fullscreen
root.focus_set()
root.bind("<Escape>", on_escape)
#doesn't work#root.protocol("WM_TAKE_FOCUS", on_focus)
canvas = tk.Canvas(root)
canvas.grid(row=0)
cbutton = tk.Button(root, text = "Run Child", width=50, height=50, bg = "green", compound = "top", command = do_something)
lab = tk.Label(canvas, text = 'Output Here')
lab.grid(row=0, column=1)
cbutton.grid(row=1, column=0)
# --- start ---
root.mainloop()
childgui.py
from tkinter import *
class app(Frame):
def __init__(self, master):
Frame.__init__(self, master=None)
self.master.title("Child Process")
self.master.geometry("500x200")
Button(self.master, text="Grandchild", command=self.dialog).pack()
self.data = StringVar()
self.data.set("Here is the data")
Label(self.master, textvariable=self.data).pack()
def dialog(self):
d = MyDialog(self.master, self.data, "Grandchild", "Enter Data")
self.master.wait_window(d.top)
class MyDialog:
def __init__(self, parent, data, title, labeltext = '' ):
self.data = data
self.rt = parent
self.top = Toplevel(parent)
self.top.transient(parent)
self.top.grab_set()
self.top.geometry("300x100")
if len(title) > 0: self.top.title(title)
if len(labeltext) == 0: labeltext = 'Data'
Label(self.top, text=labeltext).pack()
self.top.bind("<Return>", self.ok)
self.e = Entry(self.top, text=data.get())
self.e.bind("<Return>", self.ok)
self.e.bind("<Escape>", self.cancel)
self.e.pack(padx=15)
self.e.focus_set()
b = Button(self.top, text="OK", command=self.ok)
b.pack(pady=5)
def ok(self, event=None):
print ("The data:", self.e.get())
self.data.set(self.e.get())
self.top.destroy()
def cancel(self, event=None):
self.top.destroy()
def main():
root = Tk()
a = app(root)
root.mainloop()
if __name__ == '__main__':
main()
Edit: I should have mentioned the child gui is an app that is not mine. I only created this one for the example code to show the issue. While self.top.attributes may work, the actual child app is pretty large and I don't want to change it if I can avoid it. I don't have problems getting the focus, which is actually the problem. The main gui gets the focus back causing the subprocess to go behind. When the main gui is set to fullscreen (delete this to see #don't run this as the subprocess blocks #) the main gui is now stuck waiting for the child to close which you can't get to with the mouse
I am new to python and am trying to create an application that displays different information like a clock, current news, notice board etc.
I got the clock to work however I am encountering a few bugs. One is that a smaller window launches when the application does. I thought this was something to do with the self.root = tk.Tk() in the initialisation however doing anything to this line produces errors.
The other bug is that while the background image (0.png) used to fill up the entire screen as it is the same size as my monitor, when I added the clock to the application, the image is shifted to the bottom right of the screen, leaving a small white line to the top and left of the screen. I have tried to fix this by messing with the panel.pack changing it to grid and place however both of this did nothing to the lines. I feel like something is overwriting this line.
None of these bugs are showing up in the console and I don't know what to do. Here is the code I am running:
from tkinter import *
from PIL import ImageTk, Image
import os
import time
import tkinter as tk
class App(Tk):
def __init__(self):
self.root = tk.Tk()
self.label = tk.Label(text="",font=('comic',50,'bold'),bg = '#464545',fg = '#1681BE')
self.label.place(height = 206,width = 487, x = 1384, y = 824)
self.update_clock()
self.root.mainloop()
def update_clock(self):
now = time.strftime('%H:%M:%S')
self.label.configure(text=now)
self.root.after(1000, self.update_clock)
root = Tk()
img = ImageTk.PhotoImage(Image.open("0.png"))
panel = Label(root, image = img)
panel.pack()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.overrideredirect(1)
app = App()
root.geometry("%dx%d+0+0" % (w, h))
root.mainloop()
I hope someone can find what's wrong with it because I certainly can't!
Since your App class inherit from Tk, you don't need to create another root window. So I gathered all your code inside the App class. When I use an image the side of my screen, I don't see any line at the top or at the left of the screen, so I hope it will work for you as well.
from PIL import ImageTk, Image
import os
import time
import tkinter as tk
class App(tk.Tk):
def __init__(self):
# call the __init__ method of Tk class to create the main window
tk.Tk.__init__(self)
# background image
img = ImageTk.PhotoImage(Image.open("0.png"))
panel = Label(self, image=img)
panel.pack()
# clock
self.label = tk.Label(self, text="", font=('comic',50,'bold'),
bg='#464545', fg='#1681BE')
self.label.place(height=206, width=487, x=1384, y=824)
self.update_clock()
# window geometry
w, h = self.winfo_screenwidth(), self.winfo_screenheight()
self.geometry("%dx%d+0+0" % (w, h))
self.overrideredirect(True)
self.mainloop()
def update_clock(self):
now = time.strftime('%H:%M:%S')
self.label.configure(text=now)
self.after(1000, self.update_clock)
app = App()
I'm trying to launch a threaded window because I have background processes that are running, but two identical windows are launching under the same thread and I'm not sure why. I'm guessing this code can be optimized! thx for any suggestions.
6/1: I made the modification as suggested to not run two windows in the main loop, and that works. The 2nd piece, is that once the button is clicked, the window is destroyed "self.root.destroy()", but if I try to open another window it will not open. I do a check before trying to launch the new window and there is only the main thread running, so the first thread is gone. Not sure what's going on and I'm not able to debug with threads running.
from Tkinter import *
import ttk
import threading
import thread
from pdctest.test_lib.hid_util import *
class GUI():
def __init__(self, root):
self.root = root # root is a passed Tk object
self.root.title("GUI--->user instruction window")
self.frame = Frame(self.root)
self.frame.pack()
self.label0 = Label(self.frame, text=" ")
self.label0.configure(width=50, height=1)
self.label0.pack()
self.label = Label(self.frame, text="GUI--->execute a SKP on HS within 3s...")
self.label.configure(width=50, height=1)
self.label.pack()
self.button = Button(self.root, text=" GUI--->then click this button ", command=self.buttonWasPressed, fg = 'black', bg = 'dark orange')
self.button.configure(width=40, height=5)
self.button.pack(pady=25)
def removethis(self):
print("GUI--->in removethis")
self.root.destroy()
def buttonWasPressed(self):
print( "GUI--->inside buttonWasPressed: the button was pressed! " + '\r')
self.removethis()
print("GUI--->leaving buttonWasPressed")
def guiSKP(self):
#root = Tk()
#window = GUI(root)
#root.mainloop()
# modified 6/1, fixes multi-window issue
self.root.mainloop()
class GUI_SKP_Thread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
root = Tk()
window = GUI(root)
window.guiSKP()
def launch_SKP_thread():
print("beginning launch_SKP_thread" + '\r')
thread_SKP = GUI_SKP_Thread("GUI_SKP_Thread")
thread_SKP.start()
print("exiting launch_SKP_thread" + '\r')
def whatsRunning():
t = threading.enumerate()
print("--------------->whatsRunning")
print t
if __name__ == '__main__':
launch_SKP_thread()
# trying to launch 2nd window
whatsRunning()
time.sleep(4)
whatsRunning()
launch_SKP_thread()
I't not really sure what you're trying to do with the program. But I'm sure about one thing, that is, you are trying to run two frames in the same mainloop. You defined window twice in different locations, meaning that there are two frames/windows. Once in guiSKP in GUI, and once in run in GUI_SKP_Thread.
root = Tk()
window = GUI(root)
So, you should change the text in guiSKP from:
root = Tk()
window = GUI(root)
root.mainloop()
To simply:
self.root.mainloop()
I added the self to make sure it runs its own root.mainloop()
I am having two or more python Tkinter files. Each file is opening one window, how can run all the Tkinter windows functionality in one main window.
Ex : I have two files one is usbcam.py which will open USB camera and give the video steaming and the other one is ipcam.py it opens the IP camera and give the live streaming.This two files are opening in two windows how can make this to work in one window
usbcam.py
import cv2
import PIL.Image
import PIL.ImageTk
import Tkinter as tk
def update_image(image_label, cv_capture):
cv_image = cv_capture.read()[1]
cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
pil_image = PIL.Image.fromarray(cv_image)
pil_image.save('image3.jpg')
tk_image = PIL.ImageTk.PhotoImage(image=pil_image)
image_label.configure(image=tk_image)
image_label._image_cache = tk_image # avoid garbage collection
root.update()
def update_all(root, image_label, cv_capture):
if root.quit_flag:
root.destroy() # this avoids the update event being in limbo
else:
update_image(image_label, cv_capture)
root.after(10, func=lambda: update_all(root, image_label, cv_capture))
if __name__ == '__main__':
cv_capture = cv2.VideoCapture()
cv_capture.open(0) # have to use whatever your camera id actually is
root = tk.Tk()
setattr(root, 'quit_flag', False)
def set_quit_flag():
root.quit_flag = True
root.protocol('WM_DELETE_WINDOW', set_quit_flag) # avoid errors on exit
image_label = tk.Label(master=root) # the video will go here
image_label.pack()
root.after(0, func=lambda: update_all(root, image_label, cv_capture))
root.mainloop()
ipcam.py
import cv2
import numpy as np
import PIL.Image
import PIL.ImageTk
import Tkinter as tk
import urllib
stream = urllib.urlopen("http://192.168.2.195:80/capture/scapture").read()
bytes_ = ''
def update_image(image_label):
global bytes_
bytes_ += stream.read(1024)
a = bytes_.find('\xff\xd8')
b = bytes_.find('\xff\xd9')
if (a != -1) and (b != -1):
jpg = bytes_[a:b+2]
bytes_ = bytes_[b+2:]
cv_image = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),
cv2.CV_LOAD_IMAGE_COLOR)
cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
pil_image = PIL.Image.fromarray(cv_image)
tk_image = PIL.ImageTk.PhotoImage(image=pil_image)
image_label.configure(image=tk_image)
image_label._image_cache = tk_image # avoid garbage collection
root.update()
def update_all(root, image_label):
if root.quit_flag:
print "coming if"
root.destroy() # this avoids the update event being in limbo
else:
print "coming else"
update_image(image_label)
root.after(1, func=lambda: update_all(root, image_label))
def timer(interval = 100):
root.after(0, func=lambda: update_all(root, image_label))
#.................................................................................................
root.after(interval, timer)
if __name__ == '__main__':
root = tk.Tk()
setattr(root, 'quit_flag', False)
def set_quit_flag():
root.quit_flag = True
root.protocol('WM_DELETE_WINDOW', set_quit_flag)
image_label = tk.Label(master=root) # label for the video frame
image_label.pack()
root.after(2, func=lambda: update_all(root, image_label))
# timer()
root.mainloop()
You need to designate one script as the main script, and in that one you can import the other. Here's an example of doing this using a simple subclass of the Frame widget:
The primary script (tkA.py):
from Tkinter import *
from tkB import Right # bring in the class Right from secondary script
class Left(Frame):
'''just a frame widget with a white background'''
def __init__(self, parent):
Frame.__init__(self, parent, width=200, height=200)
self.config(bg='white')
if __name__ == "__main__":
# if this script is run, make an instance of the left frame from here
# and right right frame from tkB
root = Tk()
Left(root).pack(side=LEFT) # instance of Left from this script
Right(root).pack(side=RIGHT) # instance of Right from secondary script
root.mainloop()
The secondary script (tkB.py):
from Tkinter import *
class Right(Frame):
'''just a frame widget with a black background'''
def __init__(self, parent):
Frame.__init__(self, parent, width=200, height=200)
self.config(bg='black')
if __name__ == "__main__":
# if this script is run, just do this:
root = Tk()
Right(root).pack()
root.mainloop()
Hope that helps.
First, you need to include it in the top. So in the top of ipcam.py write 'import usbcam' (without quotations).