tkinter entry、button与画图的结合

这篇博客介绍如何结合tkinter的entry和button组件,利用matplotlib动态更新图形。用户输入内容后,通过button触发函数,将输入值转换并绘制成静态图。在处理输入时,需要注意小数点可能导致的转化错误,可以使用float和int进行转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

输出静态图:

  • button(command = 函数)
  • def 函数():
  • Figure, Axes = plt.subplots( figsize = (2, 2) )
        渲染 = FigureCanvasTkAgg( Figure, 窗口 )
        渲染 .get_tk_widget().place(x = 10, y = 50)
  • plt.图形
# Button按钮,Label标签,Entry输入框,Text文本框参数属性详解:https://blog.youkuaiyun.com/qq_47699076/article/details/108874815
# 给Entry控件设置默认值:https://blog.youkuaiyun.com/weixin_42683052/article/details/119116788
# 制作计算器并常见问题解答:https://blog.youkuaiyun.com/weixin_42683052/article/details/116429443

# 如果使用lambda匿名函数,command = lambda : fun() 必须要有括号,否则表达式计算不会出结果;
# 并且如果使用lambda匿名函数,公式顺序就没关系,放在前后都可以。
# 如果没有使用lambda匿名函数,则command = fun() 不能有括号,并且函数 fun() 的顺序要放在调用该公式的控件的前面。

import tkinter as tk

import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False

窗口 = tk.Tk()
窗口 .geometry("200x200") # 宽x长

输入 = tk.Entry(窗口, width = 10)
输入 .place(x = 0, y = 0)

按钮 = tk.Button(窗口, width = 5, text = "按钮", command = lambda:函数())
按钮 .place(x = 0, y = 20)

def 函数():
    获取 = 输入.get()
    Figure, Axes = plt.subplots( figsize = (2, 2) )
    渲染 = FigureCanvasTkAgg( Figure, 窗口 )
    渲染 .get_tk_widget().place(x = 10, y = 50)
    plt.bar(
        x = [1,2,3],
        height = [1,2,3],
        color = '#1eafae')
    plt.title(获取)

窗口.mainloop()

根据输入内容,更新图

  • button(command = 函数)
  • def 函数():
  • 列表 = [ ]
  • Figure, Axes = plt.subplots( figsize = (2, 2) )
        渲染 = FigureCanvasTkAgg( Figure, 窗口 )
        渲染 .get_tk_widget().place(x = 10, y = 50)
  • 列表.append(输入内容)
  • plt.画图
import tkinter as tk

import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False

窗口 = tk.Tk()
窗口 .geometry("500x500")

输入 = tk.Entry(窗口, width = 20)
输入 .place(x = 0, y = 0)

按钮 = tk.Button(窗口, width = 20, text = "输入一个数字", command = lambda:函数())
按钮 .place(x = 0, y = 20)

横轴 = []
纵轴 = []
标题 = []

def 函数():
    获取 = int(输入.get())
    
    Figure, Axes = plt.subplots( figsize = (5, 5) )
    渲染 = FigureCanvasTkAgg( Figure, 窗口 )
    渲染 .get_tk_widget().place(x = 10, y = 50)
        
    横轴 .append(获取)    
    纵轴 .append(sum(横轴))
    标题 .append(获取)
    
    plt  .bar(
        x      = 横轴,
        height = 纵轴)
    
    plt.title("输入的数字为:" + str(标题))
    
窗口 .mainloop()

笔记:

  • 获取 = int(输入.get()) 
  • 输入小数会报错,因为不能直接将包含小数点的字符串转化为整数,需要先将字符串转换为浮点数float。float(输入.get()) 
  • 然后再int()   向零取整
  • 或者round() 四舍五入取整,但是遇到0.5会向零取整,大于0.5才会向外取整
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值