0

I have a class - code below - which works flawlessly when called from if __name__ == '__main__': but when I call it from another .py file it spits an error. Apologies if this is a basic mistake on my part, but I tried a LOT of stuff and nothing seemed to work, would really love some help!

The error:

File "c:\Users\...\test.py", line 6, in <module>       
    app = Screenshot(root)
  File "c:\Users\...\Screenshot.py", line 18, in __init__
    self.master_screen = Toplevel(root)
NameError: name 'root' is not defined

The Class:

import time
from tkinter import Toplevel, Canvas, Frame, BOTH, YES, Tk
import pyautogui
import datetime

class Screenshot():
    
    def __init__(self, master):
        self.master = master
        self.rect = None
        self.x = self.y = 0
        self.start_x = None
        self.start_y = None
        self.curX = None
        self.curY = None
        
        self.master_screen = Toplevel(root)
        self.master_screen.title("Fenify")
        self.master_screen.attributes("-transparent", "blue")
        self.picture_frame = Frame(self.master_screen)
        self.picture_frame.pack(fill=BOTH, expand=YES)
        self.createScreenCanvas()

    #TakeScreenshot
    def takeBoundedScreenShot(self, x1, y1, x2, y2):
        ...
    #Window
    def createScreenCanvas(self):
        ...
    #Controls
    def on_button_press(self, event):
        ...

    def on_button_release(self, event):
        ...
    def on_right_click(self, event):
        ...
    def on_move_press(self, event):
        ...
    #Exit
    def exit_screenshot(self):
        ...

if __name__ == '__main__':
    root = Tk()
    app = Screenshot(root)
    root.mainloop()

example of calling from another class:

import tkinter
from Screenshot import Screenshot


root = tkinter.Tk()
app = Screenshot(root)
root.mainloop()

1 Answers1

1

You want to set the parent/master of your Toplevel to self.master instead of root. root isn't defined in the scope of the Screenshot class, but the input argument master does point to it.

self.master_screen = Toplevel(self.master)
busybear
  • 10,194
  • 1
  • 25
  • 42
  • OMG THANK YOU!! it's one of those painfully obvious things that I just never saw. This is very much a learning moment for future me! –  Jan 27 '21 at 16:16