How to use a Python generator function in tkinter?

Question:

Generator functions promise to make some code easier to write. But I don’t always understand how to use them.

Let’s say I have a Fibonacci generator function fib(), and I want a tkinter application that displays the first result. When I click on a button "Next" it displays the second number, and so on. How can I structure the app to do that?

I probably need to run the generator in a thread. But how do I connect it back to the GUI?

Asked By: Andreas Haferburg

||

Answers:

Not expert in tkinter but one way is to use function StringVar to be able to update its value and using text box for output.
Try this out, hope it gives you a clue.

import tkinter as tk

fibo_list = [1,1]
def fibo():
    fibo_list.append(fibo_list[-1] + fibo_list[-2])
    variable.set(fibo_list[-1])
    show_fibo_value()

def show_fibo_value():
    text_box.insert(index='end',chars=variable.get()+'n')
root = tk.Tk()
variable = tk.StringVar()
text_box = tk.Text()
text_box.pack()
button = tk.Button(root, text="Next", command=fibo)
button.pack()

root.mainloop()
Answered By: pouya

You don’t need a thread for this particular problem. You just need to instantiate the generator, then use next to get a new value each time the button is pressed.

Here’s a simple example:

import tkinter as tk

def fibonacci_sequence():
    '''Generator of numbers in a fibonacci sequence'''
    a,b = 1,1
    while True:
        yield a
        a,b = b, a+b

def do_next():
    '''Updates the label with the next value from the generator'''
    label.configure(text=next(generator))

root = tk.Tk()
label = tk.Label(root, text="")
button = tk.Button(root, text="Next", command=do_next)
label.pack(side="top")
button.pack(side="bottom")

# Initialize the generator, then us it to initialize
# the label
generator = fibonacci_sequence()
do_next()

root.mainloop()
Answered By: Bryan Oakley
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.