英文:
How to use a Python generator function in tkinter?
问题
生成器函数承诺能让一些代码更容易编写。但我并不总是理解如何使用它们。
假设我有一个名为fib()
的斐波那契生成器函数,并且我想创建一个tkinter
应用程序来显示第一个结果。当我点击一个名为“Next”的按钮时,它会显示第二个数字,依此类推。我该如何构建这个应用程序呢?
我可能需要在一个线程中运行生成器。但如何将其与GUI 连接起来呢?
英文:
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?
答案1
得分: 3
不需要为这个特定问题创建一个线程。只需实例化生成器,然后使用next
来获取每次按下按钮时的新值。
以下是一个简单的示例:
import tkinter as tk
def fibonacci_sequence():
'''斐波那契数列生成器'''
a, b = 1, 1
while True:
yield a
a, b = b, a + b
def do_next():
'''更新标签以显示生成器的下一个值'''
label.configure(text=next(generator))
root = tk.Tk()
label = tk.Label(root, text="")
button = tk.Button(root, text="下一个", command=do_next)
label.pack(side="top")
button.pack(side="bottom")
# 初始化生成器,然后用它来初始化标签
generator = fibonacci_sequence()
do_next()
root.mainloop()
希望这有所帮助!
英文:
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()
答案2
得分: 2
不精通tkinter,但一种方法是使用StringVar函数来更新其值,并使用文本框进行输出。
试试这个,希望能给你一些线索。
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()
英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论