devinxxxd
devinxxxd

Reputation: 63

How to print text in two separate windows with canvas in it?

I want to print the text AAAAAAA in one window and BBBBBBB in another one but how do I do that using canvas?

from tkinter import*

root = Tk()
canvas = Canvas(root)

canvas.pack(fill=BOTH, expand=1) # Stretch canvas to root window size.

root.wm_geometry("794x370")
root.title('Map')

def toplevel():
    top = Toplevel()
    top.title('Optimized Map')
    top.wm_geometry("794x370")
    optimized_canvas = Canvas(top)
    optimized_canvas.pack(fill=BOTH, expand=1)


toplevel()

l0 = Label(canvas, text="AAAAAAA", font= "calibri 32 bold",bg="white" )
canvas.create_window(0,70, window=l0, anchor=NW)

l1 = Label(canvas, text="BBBBBBB", font= "calibri 32 bold",bg="white" )
canvas.create_window(0,70, window=l1, anchor=NW)

root.mainloop()

Upvotes: 0

Views: 45

Answers (1)

furas
furas

Reputation: 143231

Use optimized_canvas with second label

import tkinter as tk

# ---

root = tk.Tk()

canvas = tk.Canvas(root)
canvas.pack(fill='both', expand=True)

l0 = tk.Label(canvas, text="AAAAAAA")
canvas.create_window(0, 70, window=l0, anchor='nw')

# ---

top = tk.Toplevel(root)

optimized_canvas = tk.Canvas(top)
optimized_canvas.pack(fill='both', expand=True)

l1 = tk.Label(optimized_canvas, text="BBBBBBB")
optimized_canvas.create_window(0, 70, window=l1, anchor='nw')

# ---

root.mainloop()

If you create canvas in function then it is assigned to local variable and you have to return it and assign to external/global variable to use it.

import tkinter as tk

# --- functions ---

def create_top(root):

    top = tk.Toplevel(root)

    local_canvas = tk.Canvas(top)
    local_canvas.pack(fill='both', expand=True)

    return local_canvas

# ---

root = tk.Tk()

canvas = tk.Canvas(root)
canvas.pack(fill='both', expand=True)

l0 = tk.Label(canvas, text="AAAAAAA")
canvas.create_window(0, 70, window=l0, anchor='nw')

# ---

optimized_canvas = create_top(root)

l1 = tk.Label(optimized_canvas, text="BBBBBBB")
optimized_canvas.create_window(0, 70, window=l1, anchor='nw')

# ---

root.mainloop()

Upvotes: 1

Related Questions