Python中Tkinter按钮触发图表却立即显示的问题排查与解决
问题分析与解决方法
问题根源
你的代码中,按钮的command参数直接写了click_graph(left, height)——这会在程序初始化按钮时就立刻执行click_graph函数,而不是等待按钮点击时才触发。command需要的是一个可调用对象(比如函数本身),而不是函数调用后的返回值。
解决方法
下面提供两种简单有效的修复方式:
方法1:使用lambda表达式
用lambda匿名函数包装带参数的函数调用,这样只有点击按钮时才会执行目标函数:
button = tk.Button(root, text= "Graph", command=lambda: click_graph(left, height))
方法2:使用functools.partial
通过functools.partial预先绑定函数参数,生成一个新的可调用对象:
import functools # 在win函数内修改按钮定义 button = tk.Button(root, text= "Graph", command=functools.partial(click_graph, left, height))
修复后的完整代码(lambda版本)
import matplotlib.pyplot as plt import tkinter as tk from tkinter.ttk import * def click_graph(left, height): plt.bar(left, height, width = 1, color = ['grey', 'black']) plt.show() def win(left, height): root = tk.Tk() button = tk.Button(root, text= "Graph", command=lambda: click_graph(left, height)) button.pack() button.place(x=10, y=100) root.mainloop() def main(): left = [1, 2, 3, 4, 5] height = [10, 24, 36, 40, 5] win(left, height) if __name__ == '__main__': main()
内容的提问来源于stack exchange,提问作者Liubomyr Shyrokopoias
相关产品推荐
相关产品推荐

