Aleksei Grabor
Aleksei Grabor

Reputation: 163

How to run at the same time tkinter app and thread?

I need to run tkinter applications(init_main() function) and at the same time an additional thread (translate function()) that could perform some actions. As I did, it only started the application.

import threading
import tkinter as tk 
from tkinter import ttk

WIDTH = "300"
HEIGHT = "150"
LANGUAGES = ("ru", "en")

def init_main(root):
    entry_text_box = tk.Text(root)
    entry_text_box.place(width=110, height=120, x=10, y=10)

    translate_text_box = tk.Text(root)
    translate_text_box.place(width=110, height=120, x=130, y=10)

    root.mainloop()

def translate(state):
    print("Translate function run")
    while state: 
        pass


if __name__=="__main__":
    root = tk.Tk()
    root.title("Translator")    
    root.geometry(WIDTH + "x" + HEIGHT) 
    root.resizable(False, False)

    t1 = threading.Thread(target=init_main(root)) 
    t2 = threading.Thread(target=translate(1)) 
    t1.start() 
    t2.start()

Upvotes: 0

Views: 476

Answers (2)

ShayneLoyd
ShayneLoyd

Reputation: 633

I'm pretty sure they haven't fixed multithreading in python... what you are looking for is the after method. The tkinter after method. You can simply tell the application to run a function after a set amount of milliseconds.

root.after(10000, root.destroy)

or

root.after(1, translate)

multithreading can work, but it does not work well. It definitely doesn't scale. I know this doesn't allow you to pass your variable, but you will have to get creative with that.

Upvotes: 0

Henry Yik
Henry Yik

Reputation: 22503

You don't have to thread tkinter's mainloop. Also the correct syntax of Thread should be Thread(target=function,args=(arg1,arg2,...))

import threading
import tkinter as tk
import time

WIDTH = "300"
HEIGHT = "150"
LANGUAGES = ("ru", "en")

def translate(state):
    while 1:
        print("Translate function run")
        time.sleep(1)

if __name__=="__main__":
    root = tk.Tk()
    root.title("Translator")
    root.geometry(WIDTH + "x" + HEIGHT)
    root.resizable(False, False)

    t = threading.Thread(target=translate,args=(1,))
    t.start()

    entry_text_box = tk.Text(root)
    entry_text_box.place(width=110, height=120, x=10, y=10)

    translate_text_box = tk.Text(root)
    translate_text_box.place(width=110, height=120, x=130, y=10)

    root.mainloop()

Upvotes: 1

Related Questions