hey i am making a program which records desktop screen.
So what i want to do is when ever i click on my start button(tkinter Gui) in my gui window.
It should start a timer like 3.... ,2.... ,1.... in big font directly on my desktop screen and not on my tkinter window. and then my function should start.
How can i do that ..
import tkinter as tk
from tkinter import *
root = Tk()
root.title("our program")
start_cap =tk.button(text='start recording' command=start_capute)
start_cap.pack()
root.mainloop()
Not mentioning the functions and the entire code here as not necessary the code is working fine and i just want to add a new feature of the timer in it.
An minimal example:
import tkinter as tk
# from tkinter import *
def Start():
def Count(Number):
if Number == -1:
win.withdraw()
print("Start") # what you want to do
return False
NumberLabel["text"] = Number
win.after(1000,Count,Number-1)
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
win = tk.Toplevel()
win.geometry("+%d+%d"%((screen_width-win.winfo_width())/2,(screen_height-win.winfo_height())/2)) # make it in the center.
win.overrideredirect(1)
win.wm_attributes('-topmost',1) # top window
win.wm_attributes('-transparentcolor',win['bg']) # background transparent.
NumberLabel = tk.Label(win,font=("",40,"bold"),fg='white')
NumberLabel.pack()
win.after(0,lambda :Count(3))
win.mainloop()
root = tk.Tk()
root.title("our program")
start_cap = tk.Button(text='start recording',command=Start)
start_cap.pack()
root.mainloop()
Related
I want to put an image(light.gif) in the button of tkinter.
However, the image is not shown and only a small transparent box appears at the specified position.
My Code is
from tkinter import* #To use Tkinter
from tkinter import ttk #To use Tkinter
from tkinter import messagebox #To use Tkinter
import tkinter.font # To use Font
win = Tk()
win.title("Main Control")
win.geometry('450x400+100+300')
win.resizable(0,0)
def a1():
a1 = Toplevel()
a1.title("a1")
a1.geometry('450x350+560+100')
a1.resizable(0,0)
lignt_sensor_image=PhotoImage(file = 'light.gif')
light_sensor_button=Button(a1,width=15,height=8)
light_sensor_button.place=(x=275,y=200)
a1.mainloop()
newa1 = Button(win, text='A1', font=font1, command=a1, height = 5, width = 10)
newa1.place(x=50, y=30)
win.mainloop()
Please help me
You must keep a reference to the image; as it is created in a function, it was destroyed the moment the function exited.
There also were typos in your code that prevented it from running.
The following shows your image in the popup window.
import tkinter as tk
from tkinter import PhotoImage
def spawn_toplever_a1():
global light_sensor_image # <- hold the image in the global variable, so it persists
a1 = tk.Toplevel() # do not name your variables the same as your function
a1.title("a1")
a1.geometry('450x350+560+100')
light_sensor_image = PhotoImage(file='light.gif')
light_sensor_button = tk.Button(a1, image=light_sensor_image, text="my image", compound="center")
light_sensor_button.place(x=275,y=100) # <-- typo - removed '=' sign
# <-- removed call to mainloop
light_sensor_image = None # declare variable to hold the image
win = tk.Tk()
win.title("Main Control")
win.geometry('450x400+100+300')
win.resizable(0,0)
newa1 = tk.Button(win, text='A1', command=spawn_toplever_a1, height = 5, width = 10)
newa1.place(x=50, y=30)
win.mainloop()
I want to print all events that happen in my application.
I am using python 3 with pygame and I use tkinter.
import pygame
from tkinter import *
from tkinter import ttk
def main():
root = Tk()
app = soundscene(root)
while True:
for event in pygame.event.get():
print (event)
root.mainloop()
if __name__ == "__main__":
main()
This code does not run as expected because the loop blocks, which makes sense
My question is how do I make the content of the "while true" loop part of the eventloop, so it prints out all pygame events?
To receive pygame events, a pygame window / display must be initialized.
"The input queue is heavily dependent on the pygame display module. If the display has not been initialized and a video mode not set, the event queue will not really work." Pygame event documentation.
However, if you do want to use tkinter with pygame, you can embed a pygame window into a tkinter window. This however will only give pygame events when using the embedded window. Here is an example from another question:
import pygame
import tkinter as tk
from tkinter import *
import os
root = tk.Tk()
embed = tk.Frame(root, width = 500, height = 500) #creates embed frame for pygame window
embed.grid(columnspan = (600), rowspan = 500) # Adds grid
embed.pack(side = LEFT) #packs window to the left
buttonwin = tk.Frame(root, width = 75, height = 500)
buttonwin.pack(side = LEFT)
os.environ['SDL_WINDOWID'] = str(embed.winfo_id())
os.environ['SDL_VIDEODRIVER'] = 'windib'
screen = pygame.display.set_mode((500,500))
screen.fill(pygame.Color(255,255,255))
pygame.display.init()
pygame.display.update()
while True:
for event in pygame.event.get():
print(event)
pygame.display.update()
root.update()
If you are looking for a way to receive events when using tkinter widgets, you can setup bindings in tkinter. More information at this link
I have a Python code where I create a progressbar. The Tkinter environment is created in the Gui function with the progressbar and it is launched as a thread. Then in an other thread I calculate the value that the progressbar must have, but the problem is that I dont know how to update the Gui thread with the new value of the progressbar. Here is my code:
import tkinter as tk
from tkinter import ttk
import thread
def Gui():
root = tk.Tk()
root.geometry('450x450')
root.title('Hanix Downloader')
button1 = tk.Button(root, text='Salir', width=25,command=root.destroy)
button1.pack()
s = ttk.Style()
s.theme_use('clam')
s.configure("green.Horizontal.TProgressbar", foreground='green', background='green')
mpb = ttk.Progressbar(root,style="green.Horizontal.TProgressbar",orient ="horizontal",length = 200, mode ="determinate")
mpb.pack()
mpb["maximum"] = 3620
mpb["value"] = 1000
root.mainloop()
def main():
while True:
#Calculate the new value of the progress bar.
mpb["value"] = 100 #Does not work
root.update_idletasks()#Does not work
#Do some other tasks.
if __name__ == '__main__':
thread.start_new_thread( Gui,() )
thread.start_new_thread( main,() )
The error I get is that mpb and root do no exist. Thanks in advance.
You should get error because mpb and root are local variables which exist only in Gui but not in main. You have to use global to inform both functions to use global variables - and then main will have access to mpb created in Gui
I also add time.sleep(1) before while True: because sometimes main may start faster then Gui and it may not find mpb (because Gui had no time to create progressbar)
import tkinter as tk
from tkinter import ttk
import _thread
import time
def Gui():
global root, mpb
root = tk.Tk()
button1 = tk.Button(root, text='Exit', command=root.destroy)
button1.pack()
mpb = ttk.Progressbar(root, mode="determinate")
mpb.pack()
mpb["maximum"] = 3000
mpb["value"] = 1000
root.mainloop()
def main():
global root, mpb
time.sleep(1)
while True:
mpb["value"] += 100
#root.update_idletasks() # works without it
#Do some other tasks.
time.sleep(0.2)
if __name__ == '__main__':
_thread.start_new_thread(Gui, ())
_thread.start_new_thread(main, ())
Tested on Python 3.6.2, Linux Mint 18.2
EDIT: more precisely: you need global only in Gui because it assigns values to variables
root = ..., mpb = ....
this is my code so far o cant add buttons with out it creating more windows
////////
#import tkinter
import tkinter
#import tkmessagebox(buttons)
from tkinter import *
#create a new window
window = tkinter.Tk()
#title <------ put it before .mainloop
window.title("yeahh boiiii")
#window size
window.geometry("500x500")
#set a window icon
window.iconbitmap('N:\downloads\icon.ico.ico')#<---- 8bit file name
master = Tk()
def callback():
print ("click!")
b = Button(master, text="OK", command=callback)
b.pack()
#draws the window
window.mainloop()
////////
please help
Your problem is that you create 2 instances of Tk(). This is a bad idea, and you don't need to do it since you can make your button a child of the window object:
# Import tkinter
import tkinter as tk
# Create a new window
window = tk.Tk()
# Title <------ put it before .mainloop
window.title("yeahh boiiii")
# Window size
window.geometry("500x500")
# Set a window icon
window.iconbitmap('N:\downloads\icon.ico.ico') #<---- 8bit file name
def callback():
print ("click!")
b = tk.Button(window, text="OK", command=callback)
b.pack()
# Draw the window
window.mainloop()
I also rewrote your tkinter import, because you were importing it twice...
I am working on a countdown timer for Ubuntu using Python and tkinter.
I have created most of the parts and now I want my app to be able run without appearing in Unity panel or Alt-Tab switching sequence. Is there any way to do this?
And also I'd like to whether it is possible to create a moveable window without the title bar. I tried root.overrideredirect(1).
But with it I am unable to move the window.
Here's the code for my program.
#!/usr/bin/python3
import tkinter as tk
from tkinter import ttk
from tkinter import TOP,LEFT
import time
import datetime
import sys
class Countdown(ttk.Frame):
def __init__(self,parent=None, endDate=None):
ttk.Frame.__init__(self,parent)
self.style = ttk.Style()
self.style.theme_use("clam")
self.pack()
endDate = endDate.split("/")
self.endTime = datetime.datetime(int(endDate[2]),int(endDate[1]),int(endDate[0]))
self.setWidgets()
self.initWidgets()
def setWidgets(self):
self.dLbl = ttk.Label(self,text="0",font="Ubuntu 14 bold")
self.dLbl.pack(padx=10,pady=10,side=LEFT)
self.hLbl = ttk.Label(self,text="0",font="Ubuntu 14 bold")
self.hLbl.pack(padx=10,pady=10,side=LEFT)
self.mLbl = ttk.Label(self,text="0",font="Ubuntu 14 bold")
self.mLbl.pack(padx=10,pady=10,side=LEFT)
def getTimeDelta(self):
self.curDate = datetime.datetime.now()
self.diff = self.endTime - self.curDate
self.tSec = self.diff.total_seconds()
self.days = self.diff.days
h = int(((self.tSec) - self.days*24*60*60)/3600)
self.hours = h if h>0 else 0
m = int(((self.tSec) - (self.hours*60*60+self.days*24*60*60))/60)
self.minutes = m if m>0 else 0
self.sec = int(self.tSec - self.minutes*60)
return [self.days,self.hours,self.minutes+1]
def initWidgets(self):
def set():
dhm = self.getTimeDelta()
self.dLbl["text"]=str(dhm[0])+" Days"
self.hLbl["text"]=str(dhm[1])+" Hours"
self.mLbl["text"]=str(dhm[2])+" Mins"
self.after(1000,set)
set()
root = tk.Tk()
root.title(sys.argv[1])
app = Countdown(root, sys.argv[2])
app.mainloop()
To move a window without borders you can take a look at this question for a simple example of how to implement what you want and just keep building on top of it.
For the hiding, you could use .iconify(), theoretically minimizing the app to the tray thus hiding it, and .deiconify(), for example:
root = tk.Tk()
root.iconify()
ps. If it don't work on Ubuntu/Unity you may have to use other GUI framework with support for this behavior on Ubuntu, like GTK.
import tkinter
root = tkinter.Tk()
root.withdraw()
root.mainloop()
Will hide the window.
Make your own titlebar, like so:
import sys
import tkinter as tk
import tkinter.ttk as ttk
root = tk.Tk() #create the window
titlebar = tk.Label(root,height=2, bg='cyan', fg='navyblue', text=sys.argv[0]) #create the titlebar
resizable = ttk.Sizegrip(root) #make the window resizable
titlebar.pack(fill='both') # display the titlebar
root.overrideredirect(1) #make the window run without appearing in alt tab
#root.withdraw()
#root.deiconify()
root.geometry('200x200') #set the window size to 200x200
resizable.pack(fill='y',side='right')
def ontitlebarclicked(event):
global lastposition
lastposition=[event.x,event.y]
def ontitlebardragged(event):
global lastposition
windowposition=[int(i) for i in root.geometry().split('+')[1:]] # get the window position
diffposition=[event.x-lastposition[0],event.y-lastposition[1]]
widthheight=root.geometry().split('+')[0]
root.geometry(widthheight+'+'+str(windowposition[0]+diffposition[0])+'+'+str(windowposition[1]+diffposition[1]))
titlebar.bind('<Button-1>',ontitlebarclicked)
titlebar.bind('<Button1-Motion>',ontitlebardragged)
titlebar.focus_force()