You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter项目数组append丢失历史值、Iniciar缺data参数报错求助

问题修复方案

1. 追加数据仅保留最新值问题

  • 根因:agregar函数内每次触发都会重新初始化局部变量data为固定初始数组[1, 3, 5, 7, 9],且data为函数局部作用域变量,函数执行结束后就会被销毁,无法保存历史追加的内容
  • 修复逻辑:将data定义为全局变量,仅在程序初始化时赋值一次,agregar函数内直接操作全局data做追加即可

2. Iniciar参数缺失报错问题

  • 根因:
    • 定义Iniciar函数时声明了需要接收data参数,但Tkinter的Button组件绑定command回调时默认不会传递任何参数,触发调用时就会报参数缺失
    • 原Iniciar函数内调用dibujar(a)时,变量a未做任何定义
  • 修复逻辑:移除Iniciar函数的冗余入参,内部直接调用全局data数组传给dibujar方法

修复后完整代码

from tkinter import * 
from tkinter import ttk 
from array import *
import random 

tk = Tk()
tk.title('Bubble Sort')
tk.maxsize(900, 600)
tk.config(bg = 'black')

#Variables
algoritmo = StringVar()
# 全局data数组,仅初始化一次
data = array('i', [1, 3, 5, 7, 9])

#comandos 

def dibujar(data):
    if not data:
        return
    c.delete("all") 
    cHeight = 380
    cWidth = 600 

    #para escalar 
    algoWidth = cWidth /  (len(data) + 1)
    offset = 20
    spacing = 10

    tamData = [i / max(data) for i in data]

    for i, height in enumerate(tamData):
        #top left
        x0 = i * algoWidth + offset + spacing
        y0 = cHeight - height * 50

        #botom right
        x1 = (i+1) * algoWidth + offset
        y1 = cHeight 

        c.create_oval(x0,y0,x1,y1, fill = 'red')
        c.create_text(x0+2,y0, anchor = SW, text=str(data[i]))

# 移除冗余的data入参
def Iniciar():
    print("Se selecciono: " + algoritmo.get())
    # 传入全局data变量
    dibujar(data)

def agregar():
    global data
    input =  int(inputVal.get())
    data.append(input)

    print("valor input:")
    print(input)
    print(str(data))
    # 追加后直接刷新视图,可选配置
    dibujar(data)


def limpiar():
    global data
    data = array('i', [])
    c.delete("all") 
    

#Frame
box = Frame(tk, width = 600, height = 200, bg = 'black' )
box.grid(row = 0, column = 0, padx=10, pady=5)
c = Canvas(tk, width = 600, height = 380,  bg = 'grey')
c.grid(row = 1, column = 0, padx=10, pady=5)

#UI
#Row-0
label = Label(box, text='Lista Algoritmos: ', font = ("Arial",15), borderwidth=1, bg = "black" , fg = 'white')
label.grid(row=0,column=0,  padx=5, pady=5, sticky = W)

menu = ttk.Combobox(box, textvariable = algoritmo, values=['BUBBLE SORT', 'MERGE SORT', 'HASH TABLES', 'ARBOL AVL', 'ARBOLES ROJO Y NEGRO'])
menu.grid(row=0, column=1, padx=5, pady=5)
menu.current(0)

botonStart = Button(box, text = 'Iniciar', command = Iniciar, bg = 'lime green')
botonStart.grid(row = 0, column = 2, padx = 5, pady = 5)

#Row-1 
label = Label(box, text='Insertar valor: ', font = ("Arial",15), borderwidth=1, bg = "black" , fg = 'white')
label.grid(row=1,column=0, padx = 5, pady = 5, sticky = W)
inputVal = Entry(box)
inputVal.grid(row=1,column=1, padx = 5, pady = 5, sticky = W)

botonAdd = Button(box, text = 'Agregar', command = agregar, bg = 'lime green')
botonAdd.grid(row = 1, column = 2,  padx = 5, pady = 5, sticky = W)

botonClear = Button(box, text = 'Limpiar', command = limpiar, bg = 'lime green')
botonClear.grid(row = 1, column = 3,  padx = 5, pady = 5, sticky = W)


tk.mainloop()

额外优化说明

  • 新增了dibujar函数的空数组判断,避免空数据时max(data)抛出异常
  • 修改limpiar函数逻辑,清空画布的同时也清空全局data数组
  • 追加数据后自动刷新画布视图,不需要额外点击Iniciar也能看到新增的元素

内容的提问来源于stack exchange,提问作者Paola Vilaseca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 06:27:03