Search code examples
pythontkintertoplevel

Tkinter Toplevel inf different file/function


I am trying to create a Toplevel window, however, this Toplevel is called from a different file in the same directory within a function.

Apologies I am by no means a tkinter or python guru. Here are the two parts of the code. (snippets)

#File 1 (Main)

import tkinter as tk
from tkinter import *
import comm1
from comm1 import com1

root = tk.Tk()
root.title("")
root.geometry("1900x1314")

#grid Center && 3x6 configuration for correct gui layout
root.grid_rowconfigure(0, weight=1)
root.grid_rowconfigure(11, weight=1)
root.grid_columnconfigure(0, weight=1)
root.grid_columnconfigure(11, weight=1)

#background image
canvas = Canvas(root, width=1900, height=1314)
canvas.place(x=0, y=0, relwidth=1, relheight=1)
bckground = PhotoImage(file='img.png')
canvas.create_image(20 ,20 ,anchor=NW, image=bckground)

#command to create new Toplevel
btn1 = tk.Button(root, text='Top', command=com1, justify='center', font=("Arial", 10))
btn1.config(anchor=CENTER)
btn1.grid(row=4, column=1)

#File 2 (Toplevel)

#command for new window
def com1():
    newWindow1 = Toplevel(root)
    newWindow1.title("")
    newWindow1.geometry("500x500")
    entry1 = tk.Entry(root, justify='center' , font=("Arial", 12), fg="Grey")
    newWindow1.pack()
    newWindow1.mainloop()

The weird part is this worked perfectly for a few minutes and without changing any code it just stopped working. Where am I going wrong?


Solution

  • You need to pass root as an argument to com1

    Also, you only need to start mainloop once, and that should probably be in the main file. You do not need to call it each time you create a new window.