Search code examples
python-3.xbuttontkintertkinter-canvastoplevel

How to create a button in the Toplevel in tkinter


I am getting an error while i am trying to create a button on the Toplevel in tkinter. I am using python3.

This is for my own experience im trying to make smth like an inventary checking. I dont have much experience so i didnt know what to try.

import tkinter as tk
from tkinter import *

import openpyxl


def create_search_for_window():
    top = Toplevel(root)
    canvas2 = tk.Canvas(top, width=800, height=600)
    canvas2.pack()

    Kodi = tk.Entry(top,font=('Helvetica', '20'))
    canvas2.create_window(400, 100,window=Kodi,height=100, width=200)
    kontrollo_per_kodin = tk.Button(text='Kontrollo', font=('Helvetica', 
'12'))
    canvas2.create_window(400, 200, window=kontrollo_per_kodin)


return None

book = openpyxl.load_workbook('Book1.xlsx')
sheet = book.active
columns = sheet.rows

root = Tk()


canvas1 = tk.Canvas(root, width=800, height=800)
canvas1.pack()
lab = tk.Label(root, text="aba")

kontrollo = tk.Button(text='Kontrollo', command=create_search_for_window, 
font=('Helvetica', '12'))
kontrollo.pack()
canvas1.create_window(100, 200, window=lab)
canvas1.create_window(120, 230, window=kontrollo)
root.mainloop()

My expected result is that when i press the "Kontrollo" button in the first canvas after creating the second canvas there will also be another button. The second button variable is the "kontrollo_per_kodin" in the above code.

This is the error i am getting:

_tkinter.TclError: can't use .!button2 in a window item of this canvas


Solution

  • The button needs to have the canvas or toplevel as it’s master. You can’t create a widget in one window and then move it to another.

    kontrollo_per_kodin = tk.Button(canvas2, ...)