:{ AttributeError: 'int' object has no attribute 'config' in Python

:{ AttributeError: 'int' object has no attribute 'config' in Python

那是我的代码,我有一个 config() 方法的问题,当我将它与 canvas 一起使用时,它对我不起作用,它给了我这个错误: AttributeError: 'int' 对象没有属性 'config' 所以请帮助我,因为我卡在这里....

from tkinter import ttk
from tkinter import filedialog

root = Tk()
root.title('3R')
root.geometry('350x300')
root.columnconfigure(0, weight=1)

myCanvas = Canvas(root, width=350, height=300)
myCanvas.pack(fill='both', expand=True)

#File location
Folder_Name =""
def openLocation():
    global Folder_Name
    Folder_Name = filedialog.askdirectory()
    if(len(Folder_Name))>1:
        LocError.config(text=Folder_Name, fg='green')
    else:
        LocError.config(text='Please Choose Folder!!',fg = 'red')
LocError = myCanvas.create_text(175,120, text='You must select a location',fill='red', font=('jost', 10))
#Button for location
SaveLoc = Button(root, text='Choose Path', command = openLocation)
myCanvas.create_window(130,87, anchor='nw', window=SaveLoc)

root.mainloop()```

这是工作代码:

from tkinter import *
from tkinter import ttk
from tkinter import filedialog

root = Tk()
root.title("3R")
root.geometry("350x300")
root.columnconfigure(0, weight=1)

myCanvas = Canvas(root, width=350, height=300)
myCanvas.pack(fill='both', expand=True)

#File location
Folder_Name = ""
def openLocation():
    global Folder_Name, myCanvas, LocError
    Folder_Name = filedialog.askdirectory()
    myCanvas.delete(LocError) # Delete the old sprite
    if len(Folder_Name) > 1:
        # Create a new sprite with the correct parameters:
        LocError = myCanvas.create_text(175, 120, text=Folder_Name, fill="green", font=("jost", 10))
    else:
        # Create a new sprite with the correct parameters:
        LocError = myCanvas.create_text(175, 120, text="Please Choose Folder!!", fill="red", font=("jost", 10))
LocError = myCanvas.create_text(175, 120, text="You must select a location", fill="red", font=("jost", 10))
#Button for location
SaveLoc = Button(root, text="Choose Path", command=openLocation)
myCanvas.create_window(130, 87, anchor="nw", window=SaveLoc)

root.mainloop()

变量LocError是一个int。它用于识别精灵(用于文本)。要更改它,我将其删除并使用正确的 text/fill.

创建了一个新的

您必须按如下方式更改您的 if 语句:

if len(Folder_Name) > 1:
    myCanvas.itemconfig(LocError,text=Folder_Name, fill='green')
else:
    myCanvas.itemconfig(LocError,text='Please Choose Folder!!',fill='red')

itemconfig 获取 canvas 项目的 ID 或标签并编辑其属性。 text of canvas 也没有 fg 选项,因此请将其更改为 fill