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

Tkinter中出现'int' object has no attribute '_create'错误求解决

问题解决:Tkinter创建矩形报错'int' object has no attribute '_create'

错误原因

你直接调用了Tkinter的Canvas类的create_rectangle方法,而非已实例化的Canvas对象root的方法。Tkinter组件方法必须通过实例调用,直接调用类方法会导致内部参数传递错误,触发该报错。

另外还存在一个逻辑问题:当前设置的矩形坐标guiList[c], 150, guiList[c], 350中,x起始值与x结束值完全相同,画出的是一条竖线,无法显示矩形宽度,需调整x结束值。

修正方法

  1. 将Canvas.create_rectangle改为用实例root调用:root.create_rectangle
  2. 修改矩形的x结束坐标,比如设置为guiList[c] + 80,让矩形有可见宽度
  3. 可选:调整窗口geometry为"1400x500",匹配Canvas宽度,避免部分内容被截断

修正后的完整代码

#imports
import random
from tkinter import *

#defining variables
chordTypes = ["Maj","Min","Dim","Aug","+7","+6","+4","+9","+11"] #9 values
notes = ["C", "C#/Db", "D", "D#/Eb", "E", "F", "F#/Gb", "G", "G#/Ab", "A", "A#/Bb", "B",] #12 values
guiList = []
initialChordSequence = []
top = Tk()
top.geometry("1400x500")  # 调整窗口宽度匹配Canvas

#generating the sequence randomly
for a in range(random.randint(3,7)):
    initialChordSequence.append((random.choice(notes))+(random.choice(chordTypes)))

#gui
root = Canvas(top, bg = "DarkOrange2", height = "500", width = "1400")
for b in range(12):
    guiList.append(b*100 + 100)
print(guiList)
for c in range(12):
    # 用实例root调用方法,同时调整x结束坐标
    root.create_rectangle(guiList[c], 150, guiList[c] + 80, 350, fill="white")  # 可选添加fill参数让矩形更明显
root.pack()
top.mainloop()

#outputs
print(initialChordSequence)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:33:28