Reputation: 123
I am making a gui and code is given below . when i click on copy button in the gui it gets freezed till the execution of process but i want to do other process at the same time.I did some research on Google and i got to know that if i run that process in the background then this problem gets solved. So please anyone tell me the easiest way to do it ?
Code:
import Tkinter as tk
import time
root = tk.Tk()
root.geometry('300x400')
def Number():
for i in range(100):
print(i)
time.sleep(1)
def hello():
print('Hello')
b = tk.Button(root,text='copy',command = Number)
b.pack()
b = tk.Button(root,text='display',command = hello)
b.pack()
root.mainloop()
Expected output
when I will click on copy button the function Number
should run in the background and Gui should not be freezed and at the same time if i click on display
button it should display Hello
Upvotes: 1
Views: 4450
Reputation: 705
You have to launch your number priting function in a thread.
This is a very, very rough example that knows nothing about when the launched function completes, allows you to start several counts simultaneously... you probably want to read on into threading if you want to do it properly.
import Tkinter as tk
import time
import threading
root = tk.Tk()
root.geometry('300x400')
def print_numbers(end): # no capitals for functions in python
for i in range(end):
print(i)
time.sleep(1)
def print_hello():
print('Hello')
def background(func, args):
th = threading.Thread(target=func, args=args)
th.start()
b1 = tk.Button(root,text='copy',command = lambda : background(print_numbers, (50,))) #args must be a tuple even if it is only one
b1.pack() # I would advice grid instead for Tk
b2 = tk.Button(root,text='display',command = print_hello)
b2.pack()
root.mainloop()
Upvotes: 4