0

The code works correctly, however it always throws the error "AttributeError: 'int' object has no attribute 'grid'". The problem is that if you remove the ".grid()", the image does not appear... However, the error disappears. If you position the ".grid()" one line below, separating it, the error also disappears, however the image disappears and the scrollbar loses its effect:

from tkinter import *
from tkinter import ttk
import tkinter as tk

root = Tk()

def help():

    window = tk.Toplevel(root)

    window.geometry("750x500")
        
    main_frame = Frame(window)
    main_frame.pack(fill=BOTH, expand=1)

    my_canvas = Canvas(main_frame)
    my_canvas.pack(side=LEFT, fill=BOTH, expand=1)

    my_scrollbar = ttk.Scrollbar(main_frame, orient=VERTICAL, command=my_canvas.yview)
    my_scrollbar.pack(side=RIGHT, fill=Y)

    my_canvas.configure(yscrollcommand=my_scrollbar.set)
    my_canvas.bind('<Configure>', lambda e: my_canvas.configure(scrollregion = my_canvas.bbox("all")))

    inf = tk.PhotoImage(file="image.png")

    my_canvas.create_image(1, 1, image=inf, anchor=tk.NW).grid()

help()

root.mainloop()

What I noticed is that this error occurs only when using the "tk.TopLevel()" function, if it generates the code in the tkinter master page, it results in the scrollable image without the need for ".grid()" and without errors. Does anyone have a solution to work around the error or should I just accept it as it's running? Here is the code working on the master page:

from tkinter import *
from tkinter import ttk
import tkinter as tk

root = Tk()

root.geometry("750x500")
            
main_frame = Frame(root)
main_frame.pack(fill=BOTH, expand=1)

my_canvas = Canvas(main_frame)

my_canvas.pack(side=LEFT, fill=BOTH, expand=1)

my_scrollbar = ttk.Scrollbar(main_frame, orient=VERTICAL, command=my_canvas.yview)
my_scrollbar.pack(side=RIGHT, fill=Y)

my_canvas.configure(yscrollcommand=my_scrollbar.set)
my_canvas.bind('<Configure>', lambda e: my_canvas.configure(scrollregion = my_canvas.bbox("all")))

inf = tk.PhotoImage(file="image.png")

my_canvas.create_image(7, 7, image = inf, anchor = tk.NW)

root.mainloop()
  • 1
    You don't need to (or should not) use `.grid()` on the result of `.create_image()`. The image did not show after removing `.grid()` because it is garbage collected due to same issue of this [question](https://stackoverflow.com/questions/16424091/why-does-tkinter-image-not-show-up-if-created-in-a-function). – acw1668 Mar 14 '23 at 05:21
  • Thanks for the answer. In fact, the problem is the same and I managed to solve the error by transforming the variables into global ones, adding the ".self" and removing the ".grid()". But I can't understand why when adding the ".grid()" the code works normally. It generates this error, but apparently it does not influence the final result at all. Anyway, the problem is solved. – Alexandre Estrela Mar 14 '23 at 11:57

0 Answers0