Too early to create image

Output
Executing the above code will display a window with a label and three buttons,
On the console, it will print the list of all the widgets defined in frame widget.
In order to get the information about the widgets, tkinter provides a set of methods that can be used to test the widgets in an application.

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

shippo16 opened this issue

Dec 13, 2020

· 18 comments

I was trying to make a Tkinter application with a video and a live matplotlib graph. The programs runs fine while using a webcam but stops responding at the end of video file. It raise the below errors after terminating the program.

RuntimeError: Too early to create image: no default root window

Exception ignored in: <function PhotoImage.del at 0x000001F9EB491AF0>

#Set up GUI
window = tk.Tk()  #Makes main window
window.wm_title("Social distancing detector")
window.config(background="#FFFFFF")

#Graphics window
imageFrame = tk.Frame(window, width=600, height=1000)
imageFrame.grid(row=0, column=0, padx=10, pady=2)

display1 = tk.Label(imageFrame)
display1.grid(row=1, column=0, padx=10, pady=2)  #Display 1

# matplotlib part
x=[]
y=[]

fig = Figure(figsize=(3, 2), dpi=100)
# fig = plt.axes()

a = fig.add_subplot()
a.set_xlabel('Frame no.')
a.set_ylabel('Number of violations')

canvas = FigureCanvasTkAgg(fig, master=window)
canvas.draw()
canvas.get_tk_widget().grid(row=3, column=0, ipadx=40, ipady=20)

# inside the while loop
if args["display"] > 0:
            # show the output frame
            frame1=cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
            frame1=cv2.resize(frame1, (500,350), interpolation=cv2.INTER_AREA)
            img_update = ImageTk.PhotoImage(Image.fromarray(frame1))
            display1.configure(image=img_update)
            display1.image=img_update
            display1.update()

Link for the complete code: https://pastebin.com/GFUKvXYu
Complete list of errors: https://pastebin.com/xTF4Zhjv
How do I correct these errors and what is the right syntax?
Thank you for your reply

Я пытаюсь создать небольшой класс для представления жизненно важной информации о различных GIF-файлах, которые я хочу, чтобы программное обеспечение обрабатывало. Вот мой код:

from PIL import Image
import tkinter as tk

class ListifiedGif:
    """Class containing list of frames and number of frames from GIF."""
    def __init__(self, filename):
        gif = Image.open(filename)
        self.frame_count = gif.n_frames
        self.frame_list = [tk.PhotoImage(file = filename,
                                         format = f'gif -index {i}')
                                         for i in range(gif.n_frames)]

Когда я вставляю следующее в конец файла, я получаю сообщение об ошибке.

testimg = ListifiedGif('E:\\Development\\desktop\\img\\walking_negative.gif')

print(testimg.frame_count)
print(testimg.frame_list)
Traceback (most recent call last):
  File "<module1>", line 13, in <module>
  File "<module1>", line 9, in __init__
  File "<module1>", line 9, in <listcomp>
  File "C:\Program Files\Python39\lib\tkinter\__init__.py", line 4064, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Program Files\Python39\lib\tkinter\__init__.py", line 3997, in __init__
    master = _get_default_root('create image')
  File "C:\Program Files\Python39\lib\tkinter\__init__.py", line 297, in _get_default_root
    raise RuntimeError(f"Too early to {what}: no default root window")
RuntimeError: Too early to create image: no default root window

Почему необходимо объявлять корневое окно для создания образа? Есть ли способ обойти это, чтобы я мог просто вернуть список кадров (в виде серии PhotoImages из tkinter), не беспокоясь о том, как именно выглядит окно, в котором будет использоваться изображение?

Спасибо заранее за ваше время.

Я новичок в программировании, поэтому я взял простой онлайн-проект и попытался использовать ООП, чтобы создать для него графический интерфейс, можете ли вы помочь мне с этой ошибкой:

'RuntimeError: Too early to run the main loop: no default root window'

Я убрал кнопки, чтобы было короче:

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

contact_list = [
    ['Dermot Bruce', '071 0403 6313'],
    ['Felix Kent', '071 7050 4862'],
    ['Eren Yeager', '071 4174 1560'],
    ['Roy Mustang'  '071 5173 4259'],
    ['Arietta Curtis', '071 4415 8004'],
    ['Jennifer Love', '071 8857 1196'],
]


class address_list():
    def __init__(self, *args):
        self.contact = contact_list


class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self, address_list)
        self.title = "Address Book Interface"
        self.geometry('400x400')
        self.resizable(0, 0)
        self.config(bg='lightblue')

        self.name = StringVar()
        self.number = StringVar()
        # create frame
        self.frame = Frame(self)
        self.frame.pack(side=RIGHT)

        def add_contact(contact_list):
            contact_list.append([self.name.get(), self.number.get()])
            select_set()

        # to view selected contact(first select then click on view button

        def edit(contact_list):
            contact_list[Selected()] = [self.name.get(), self.number.get()]
            select_set()

        def view(contact_list):
            NAME, PHONE = contact_list[Selected()]
            self.name.set(NAME)
            self.number.set(PHONE)

        # to delete selected contact

        def delete(contact_list):
            del contact_list[Selected()]
            select_set()

        # empty name and number field

        def reset(contact_list):
            self.name.set('')
            self.number.set('')

        # exit game window

        def exit(contact_list):
            self.destroy()

        def select_set(contact_list):
            contact_list.sort()
            select.delete(0, END)
            for name, phone in contact_list:
                enter
                code
                hereselect.insert(END, self.name)

        select_set()


if __name__ == '__main__':
    mainloop()

Я делаю камеру с opencv и tkinter на Python. У меня небольшая проблема с кодом при закрытии окна. Мне нужно регулярно обновлять окно, потому что веб-камера регулярно делает снимки и отображается в окне как видео. Итак, у меня есть цикл while, и я поставил условие True, но он выполняется даже после закрытия окна, поэтому возникает ошибка. Я пробовал много вещей разными способами, но показывает ту же ошибку. Вот мой код:


import cv2
import numpy as np
from tkinter import *
from PIL import ImageTk,Image

root1 = Tk()

root = Toplevel()
root.title("Camera v1.0")
root.configure(bg = 'black')


label = Label(root, text= "Camera v1.0",font = ("times new roman","15","bold"),bg = "black",fg = 'goldenrod2')
label.pack(side = TOP,fill = BOTH)

frame = Frame(root,bg = 'black')
frame.pack()


label2 = Label(frame,bg = 'red')
label2.pack()

btn_verify = Button(frame,text = "Take a Snapshot", font = ("times new roman","11","bold"),activebackground ='red',bg = "#bf80ff",fg="#000080",width = 15)
btn_verify.pack(side = BOTTOM,expand = False)

cap = cv2.VideoCapture(0)

while True:
    if cap:
        img = cap.read()[1]
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        img = ImageTk.PhotoImage(image = Image.fromarray(img))
        label2['image'] = img 
        root.update()
    else:
        pass

root.mainloop()

 Traceback (most recent call last):   File
 "c:\Users\swach\OneDrive\Swachchha\পাইথন দিয়ে
 মজা\Opencv_Projects\face_recognizing.py", line 49, in <module>
     img = ImageTk.PhotoImage(image = Image.fromarray(img))   File "D:\Python Interpreter\lib\site-packages\PIL\ImageTk.py", line 112, in
 __init__
     self.__photo = tkinter.PhotoImage(**kw)   File "D:\Python Interpreter\lib\tkinter\__init__.py", line 4064, in __init__
     Image.__init__(self, 'photo', name, cnf, master, **kw)   File "D:\Python Interpreter\lib\tkinter\__init__.py", line 3997, in
 __init__
     master = _get_default_root('create image')   File "D:\Python Interpreter\lib\tkinter\__init__.py", line 297, in _get_default_root
     raise RuntimeError(f"Too early to {what}: no default root window") RuntimeError: Too early to create image: no default root window

Есть ли какой-либо метод обновления, который не будет обновлять окно tkinter после уничтожения в tkinter?

Fixing Code Error: How to Resolve RuntimeError: Too Early To Create Variable: No Default Root Window

Fixing Code Error: How to Resolve RuntimeError: Too Early To Create Variable: No Default Root Window

Do you need help resolving a code error? Are you stuck with a RuntimeError: Too Early To Create Variable: No Default Root Window? Don’t worry, this article can help you resolve this issue quickly and easily.

If you are a software engineer or a programmer who regularly codes, then you know that every once in a while, you might encounter an error in your code. This can be quite frustrating, especially if you don’t know how to fix it. Fortunately, this article will provide you with the steps you need to take to resolve your RuntimeError: Too Early To Create Variable: No Default Root Window.

The first step to fixing this code error is to identify the source of the error. This can be done by checking the code for any typos, syntax errors, and other mistakes. Once these are identified and corrected, you can then continue with the next step, which is to debug the code. Debugging helps to identify any logical errors in the code, which can then be fixed.

After debugging the code, the next step is to check for any dependencies or libraries that are missing. If any of these are missing, then you need to install them in order to make sure that your code works properly. This can be done by downloading the correct version of the library from the internet and then installing it into your code.

Finally, after all the necessary steps have been taken to fix the code error, you can then execute the code to check if it works as expected. If it does, then you can be sure that you have solved your RuntimeError: Too Early To Create Variable: No Default Root Window.

With these steps, you can now easily fix the code error and resolve the RuntimeError: Too Early To Create Variable: No Default Root Window. So, take the time to read this article and apply the steps mentioned above to get your code running smoothly.

When coding in any programming language, errors can occur. One of the most common errors that you can encounter is the RuntimeError. This error is caused when code is written incorrectly and the computer is not able to understand it correctly. When this happens, the computer will throw a RuntimeError with a message that states Too Early To Create Variable: No Default Root Window without title. This can be a very confusing error, as it is not easy to understand what the problem is. Fortunately, there are some steps that you can take to resolve this error and get your code running again.

Fixing Code Error: Avoiding Too Early Creation of Variables with No Default Root Window

Are you struggling to fix code errors that involve the creation of variables with no default root window? If so, you are not alone. Many coders are faced with this common problem, but there are solutions out there.

This article will provide a step-by-step guide on how to avoid too early creation of variables with no default root window, and the best practices to keep in mind when dealing with this type of coding error. By the end of this article, you will have the knowledge and understanding to successfully fix this code error.

One of the most common causes of this coding error is when a programmer creates a variable before setting a default root window. This can occur when the programmer is not aware of the scope of the variable and does not properly set the root window. As a result, the variable is created without the default root window and this can cause the code to fail.

The first step to avoiding this coding error is to understand the scope of the variables you are creating. It is important to make sure that the variables are created within the scope of the root window. Once this is done, the next step is to set the default root window for the variables. This can be done either by using a global variable or by setting the root window as a parameter in the code.

Дополнительно:  Чем получить временный root

It is also important to make sure that the root window is set before any variables are created. This will ensure that the variables are created within the scope of the root window. Finally, it is important to keep track of the variables that have been created and make sure that they are properly destroyed when they are no longer needed.

Developers often run into code errors when attempting to create variables with no default root window without a title. This can lead to unexpected results and cause a lot of frustration. It is important to understand what causes this type of error and how to fix it in order to avoid the same issue in the future. This article will provide a comprehensive guide on how to avoid too early creation of variables with no default root window without a title.

What is Too Early Creation of Variables?

Too early creation of variables is when a variable is created before a root window with a title has been declared. This can lead to unexpected results as the root window may not contain the necessary information needed to properly initialize the variable. This can lead to errors or unexpected behavior in the code. It is important to be aware of this issue and to take steps to avoid it.

What is a Default Root Window?

A default root window is a window that is automatically created when a program is launched. It is the main window of the program and it provides the basic information and functions needed by the program. It typically contains a title bar, menu bar, and other elements that are essential for the program to run properly. Without a default root window, it is difficult to create variables as the necessary information needed to properly initialize them is not available.

Why is it Important to Avoid Too Early Creation of Variables?

It is important to avoid too early creation of variables as it can lead to unexpected results. If a variable is created before a default root window is declared, it can lead to errors or unexpected behavior in the code. This can be avoided by ensuring that a root window with a title is declared before any variables are created.

How to Fix the Error?

Code to Declare a Root Window with a Title:

root = Tk()
root.title(My Window)

This code will create a root window with a title of My Window. Once this is declared, any variables can be created without running into the same error.

Using Other Software to Fix the Error

In addition to using code to fix the error, there are other software programs that can be used as well. One example is an IDE, such as Visual Studio Code, which can be used to create and debug code. This can be used to locate and fix any errors that may be present in the code, including those related to too early creation of variables.

Conclusion

Video How to Pass Data between Multiple Windows in Tkinter
Source: CHANNET YOUTUBE CodersLegacy

Fixing Code Error: Avoiding Too Early Creation of Variables with No Default Root Window

What is the best way to avoid too early creation of variables with no default root window?

The best way to avoid too early creation of variables with no default root window is to make sure that you properly declare and initialize your variables before using them in your code. This will ensure that your code is properly structured and will help prevent any unexpected errors.


Fix Code Error: Too Early To Create Variable - No Default Root Window

Are you struggling to understand why your code is giving you an error about creating a variable too early, when there is no default root window? This can be a frustrating and difficult problem to solve, but don’t worry! This article will provide a step by step guide to help you fix this error.

First and foremost, it is important to understand the cause of this error. The error occurs when a variable is attempted to be created before the root window is created and given a value. This is a problem because the root window is not initialized and given a value until later in the code.

So how can you fix this error? The solution is to move the code that creates the variable to after the root window is created and given a value. This will allow the program to properly run and the error to be eliminated.

Now that you know how to fix the error of creating a variable too early, without a default root window, you can get back to coding! This article has provided a step by step guide to help you understand and fix this error. So don’t delay, get coding and make sure that your code is running smoothly.

When programming in any language, errors are an inevitable part of the process. One common error that pops up when using the programming language TCL is the “Too Early To Create Variable – No Default Root Window without title” error. This error is especially annoying because it prevents the code from running, and can be difficult to diagnose and fix. Fortunately, with a little bit of knowledge and some troubleshooting, it is possible to diagnose and fix this error. In this article, we will discuss the causes of the “Too Early To Create Variable – No Default Root Window without title” error and provide tips and tricks for fixing it.

What Causes Too Early To Create Variable – No Default Root Window Without Title?

The “Too Early To Create Variable – No Default Root Window without title” error occurs when the code attempts to create a variable before the root window has been created. The root window is the main window in a TCL application, and all other windows are its children. If the code attempts to create a variable before the root window has been created, the code will fail. This can happen due to a variety of reasons, including incorrect syntax, missing commands, and incorrect order of operations.

The first step in fixing the “Too Early To Create Variable – No Default Root Window without title” error is to identify the cause of the error. If the error is due to incorrect syntax, the code should be examined and corrected. If the error is due to missing commands, the necessary commands should be added. If the error is due to incorrect order of operations, the code should be re-ordered so that the root window is created before any variables are created. Once the code has been corrected, the application should be re-run and the error should be resolved.

Using Other Software To Fix Too Early To Create Variable – No Default Root Window Without Title

If the “Too Early To Create Variable – No Default Root Window without title” error persists after troubleshooting, it may be necessary to use other software to fix the error. There are a variety of programs available that can help diagnose and fix errors in TCL code. These programs can detect errors, suggest possible solutions, and even provide code to fix the errors. Using one of these programs can help ensure that the error is fixed and the application runs correctly.

Conclusion

The “Too Early To Create Variable – No Default Root Window without title” error is a common error that can be frustrating to diagnose and fix. However, with a little bit of knowledge and some troubleshooting, it is possible to diagnose and fix this error. If the error persists after troubleshooting, other software can be used to help diagnose and fix the error. With the right tools and knowledge, the “Too Early To Create Variable – No Default Root Window without title” error can be fixed quickly and easily.

Video How to Pass Data between Multiple Windows in Tkinter
Source: CHANNET YOUTUBE CodersLegacy

Дополнительно:  Пароль root antix linux

Fix Code Error: Too Early To Create Variable – No Default Root Window

What is a Too Early To Create Variable – No Default Root Window code error?

This is an error that occurs when you try to create a variable that doesn’t exist in the root window. This can occur when trying to access a variable in the global scope before it has been declared.

How do I fix the Too Early To Create Variable – No Default Root Window code error?

The best way to fix this error is to make sure that the variable is declared before it is used. This can be done by using the var keyword to declare the variable in the global scope, or by using the let keyword to declare the variable in the local scope.


Table of contents

RuntimeError: Too early to create image [duplicate]

I am trying to create an image library and to call an image from that image library in

tkinter

. But this code gives me an error:

This is the image library file

img.py

:

from tkinter import *
food_0001 = PhotoImage(file='food_0001.gif')
food_0002 = PhotoImage(file='bg.gif')

This is the file intended to open images stored in

img.py

:

from tkinter import *
import img
window = Tk()
window.title('image')
canvas = Canvas(window, width = 800, height = 800)
canvas.pack()
canvas.create_image(0,0, anchor=NW, image=food_0001)
window.mainloop()

It is because

PhotoImage()

can only be called after creation of

Tk()

.

Suggest to rewrite

img.py

to create

PhotoImage()

only when it is needed. Below is a sample way to do it:

from tkinter import *
imagelist = {
  'food_0001': ['food_0001.png', None],
  'food_0002': ['bg.png', None],
}
def get(name):
  if name in imagelist:
    if imagelist[name][1] is None:
      print('loading image:', name)
      imagelist[name][1] = PhotoImage(file=imagelist[name][0])
    return imagelist[name][1]
  return None

Then modify your main program to cater the change:

from tkinter import *
import img
window = Tk()
window.title('image')
canvas = Canvas(window, width=800, height=800)
canvas.pack()
canvas.create_image(0, 0, anchor='nw', image=img.get('food_0001'))
window.mainloop()

Of cause there are many other ways to do it and it depends on your imagination.

Tkinter RuntimeError: Too early to create image: no default root window

So I’m trying to draw an image to a tkinter canvas in python, and keep getting the error in the title. I have a reference to

tkinter.Tk()

, I’ve set it as the canvas’s master, I’ve packed the canvas, and run the mainloop. This all happens upon program start. Then, I call

gui.drawentity()

in main.py, which attempts to create an image and draw it to the canvas.

root = tk.Tk()
canvas = tk.Canvas(root, bg="green")
canvas.pack(fill=tk.BOTH, expand=True)
root.mainloop()
def drawentity(entity):
    imgPath = data.getimagepath(entity.img, entity.imgType)
    img = None
    try:
        img = tk.PhotoImage(imgPath)
        canvas.create_image(entity.x, entity.y, img)
    except IOError as e: print(e)
    finally:
        if not isinstance(img, type(None)): img.close()
e = player.Player(100, 200, "Ball_Grayed.png", 3)
gui.drawentity(e)
 cd = os.path.join(os.getcwd(), "resources")
 def getimagepath(imgName, imgType):
     return os.path.join(cd, imgType, imgName)
File "S:\Users\Sean\Google Drive\cs\personal\BallAdventure\main.py", line 12, in <module>
    gui.drawentity(e)
  File "S:\Users\Sean\Google Drive\cs\personal\BallAdventure\gui.py", line 22, in drawentity
    img = tk.PhotoImage(imgPath)
  File "C:\Users\Sean\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 4093, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Users\Sean\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 4026, in __init__
    master = _get_default_root('create image')
  File "C:\Users\Sean\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 297, in _get_default_root
    raise RuntimeError(f"Too early to {what}: no default root window")
RuntimeError: Too early to create image: no default root window

Everything looks fine to me, can anyone see what the problem is?

(see Nesi’s comment)

Too early to create image at NewWindow, Try moving the line root.destroy () before win = Tk () to avoid multiple instances of Tk () which may cause problems. Or you can specify the Tk instance to be used when initiating the PhotoImage instance: photo2 = PhotoImage (file=»img/dog1.gif», master=win).

Python Tkinter Error, «Too Early to Create Image»

So I have an assignment that I have to use Tkinter to create a board game. This is just one part of the program where I want to bring in the image of the board. But I keep on getting the error, «Too early to create image» and I’m not sure what I’m doing wrong.

Here’s my code so far:

from Tkinter import *
from pprint import pprint
# Which variable is currently updating
from variableColors import Variables
VariableIndex = 0               
VariableText = Variables[VariableIndex]
Ids = None             # Current canvas ids of the text and 4 player tokens:
                       # Will be None if not committed
VariableCoords = { }       # Where store variable and coordinates
im = PhotoImage(file="C:\Users\Kiki\Desktop\Assignment\\")
photo = can.create_image(0,0,anchor=NW, image=im)
can.pack()
root.mainloop()

Any help would be appreciated. Thanks 🙂

You forgot to declare root —

root = Tk()

.
The Tk system must be ON before using it.

Py2exe gives RuntimeError: Too early to create image

C:\python\python_ui\exe\dist>basic.exe
Traceback (most recent call last):
  File "basic.py", line 7, in <module>
  File "PIL\ImageTk.pyo", line 117, in __init__
  File "Tkinter.pyo", line 3367, in __init__
  File "Tkinter.pyo", line 3304, in __init__
RuntimeError: Too early to create image
Exception AttributeError: "'PhotoImage' object has no attribute '_PhotoImage__photo'" in <bound method PhotoImage.__del__ of <PIL.ImageTk.Ph
otoImage object at 0x02CA3A90>> ignored


basic.py

— very basic example and yes, Tk() is initialized. Also, the module versions appear to match in both IDLE() and the executable version

from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
image = Image.open("background.jpg")
photo = ImageTk.PhotoImage(image)
label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()
root.mainloop()


setup.py

— Here is my py2exe setup, and I run

python setup.py py2exe

to get the executable:

import py2exe, sys, os
from distutils.core import setup
from glob import glob
sys.path.append("C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\redist\\x86\\Microsoft.VC90.CRT")
sys.argv.append('py2exe')
setup( 
  data_files = [
      ("Microsoft.VC90.CRT", glob(r'C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT\*.*')),
      ("background.jpg"),
      ],
  options = {         
    'py2exe' : {
        'compressed': 1, 
        'optimize': 2,
        'bundle_files': 3, 
        'dist_dir': 'dist',  
        'dll_excludes': ["MSVCP90.dll"]
        }
    },                   
  zipfile=None, 
  console = [{'script':'user_code.py'}, {'script':'basic.py'}],
)

Version Information matches, and printing the image gives same values when run from IDLE() as it does the executable:

  • pil 3.4.2
  • tkinter $Revision: 81008 $
  • PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=179×119 at 0x3DF6A50
  1. Uninstall 32bit python27.12
  2. install 32bit python27.10 // 12 will probably work too
  3. pip install pip
  4. pip install Pillow
  5. install MSVC9
  6. pip install py2exe
  7. remove all prior distribution builds from older py2exe
  8. regenerate executable

Comments

@shippo16

Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

Show more details
actor = ‘serhiy.storchaka’
assignee = ‘serhiy.storchaka’
closed = True
closed_date =
closer = ‘serhiy.storchaka’
components = [‘Tkinter’]
creation =
creator = ‘shippo_’
dependencies = []
files = [‘49681’]
hgrepos = []
issue_num = 42630
keywords = [‘patch’]
message_count = 18.0
messages = [‘382944’, ‘382946’, ‘382949’, ‘382951’, ‘382974’, ‘382978’, ‘383002’, ‘383003’, ‘383018’, ‘383041’, ‘383043’, ‘383081’, ‘383082’, ‘383087’, ‘383106’, ‘383366’, ‘383369’, ‘383381’]
nosy_count = 3.0
nosy_names = [‘serhiy.storchaka’, ‘epaine’, ‘shippo_’]
pr_nums = [‘23781’, ‘23853’, ‘23854’]
priority = ‘normal’
resolution = ‘fixed’
stage = ‘resolved’
status = ‘closed’
superseder = None
type = ‘behavior’
url = ‘https://bugs.python.org/issue42630’
versions = [‘Python 3.8’, ‘Python 3.9’, ‘Python 3.10’]»>

   ::
  
  
  
   ::
  
  []
   ::
  
  []
  []
  []
  
  []
  
  [, , , , , , , , , , , , , , , , , ]
  
  [, , ]
  [, , ]
  
  
  
  
  
  
  
  [, , ]

@shippo16




Copy link

I think it would be nice to add:

335 > if not master:
336 > raise RuntimeError(‘a valid Tk instance is required.’)

to lib/tkinter/init.py, and not rely on this unclear AttributeError.

Could it be assigned to me, please?

Best Regards
Ivo Shipkaliev

@shippo16




Copy link

@shippo16




Copy link

333 > if not master:
334 > if not _default_root:
335 > _default_root = Tk()
336 > master = _default_root
337 > self._root = master._root()

@shippo16
shippo16

changed the title
Variable.__init__ raise a RuntimeError instead of obscure AttributeError

Variable.__init__ to raise a RuntimeError instead of obscure AttributeError

Dec 14, 2020

@shippo16




Copy link

Sorry, we need «global» too:

333 > if not master:
334 > global _default_root
335 > if not _default_root:
336 > _default_root = Tk()
337 > master = _default_root
338 > self._root = master._root()

@E-Paine

+1 I agree the current AttributeError is not suitable.

I would just copy the code from Lib/tkinter/init.py:2524 (or even better: refactor it into its own method to avoid duplication). The code there, though, would raise a similar AttributeError if the default root is disabled, so I suggest that needs a changing to possibly a TypeError (i.e. missing ‘master’ argument). I assume you are alright to create a PR for this?

Please revert the «resolution» field as this is intended to be the reason for issue closure.

@E-Paine
E-Paine

added


3.8

only security fixes

only security fixes

only security fixes

Dec 14, 2020

@E-Paine
E-Paine

changed the title
Variable.__init__ to raise a RuntimeError instead of obscure AttributeError

Variable.__init__ raises obscure AttributeError

Dec 14, 2020

@serhiy-storchaka

Actually it may be worth to reuse setup_master() from tkinter.ttk.

But I am not sure what is better: raise error (RuntimeError) if the global function uses _default_root which is not initialized, or create the root widget implicitly. Currently AttributeError or NameError is raised.

@shippo16




Copy link

The current implementation is already relying on _some_ master anyway:

335 > self._root = master._root()

So, initializing a default root, if one isn’t present, shouldn’t break anything. And reusing setup_master() is a good idea. Maybe:

333 > master = setup_master(master)
334 > self._root = master._root()

from tkinter.ttk import setup_master

leads to a circular import error. I’ll look into this.

@E-Paine

I guess my question is whether we are limiting most changes to just __init__.py or whether we want to do more of a cleanup throughout the tkinter module (e.g. tkinter.dialog.Dialog can be neatened and no longer needs to inherit the Widget class).

@shippo16




Copy link

Are you gonna submit a PR so I can eventually use _setup_master() in my PR?

@E-Paine

Are you gonna submit a PR

I think I assumed you would incorporate it into your PR unless you would prefer it to be separate?

@serhiy-storchaka

Don’t haste. I am currently working on a large PR with many tests.

@shippo16




Copy link

Thank you very much, fellows!

I understand your concern: «But I am not sure what is better: raise error (RuntimeError) if the global function uses _default_root which is not initialized, or create the root widget implicitly.»

Дополнительно:  What is the root of Christianity?

In the new _get_default_root() function, first we check if Support Default Root in on:

290 > if not _support_default_root:

But later on we do:

At this point, if «what» evaluates to True, we raise a RuntimeError. But at this same time Support Default Root is on, and there is no default root. And clearly: «.. no default root window» error contradicts the «_support_default_root» idea.

So further on, assuming Support Default Root is on, if we instantiate a Variable with master=None, we would get: «Too early to create variable: no default root window», which makes no sense.

In my view, we should always create a default root if it’s needed, provided that _support_default_root is True. Simply: Support Default Root must lead to a default root.

@E-Paine

In my view, we should always create a default root if it’s needed

I somewhat disagree. I think Serhiy has done a very good job (in what I’ve reviewed so far) of balancing when a new root should or shouldn’t be created (e.g. does it make sense to create a new root when calling getboolean as this should only be called once there is a Tcl object to be processed?).

We also have the consideration of backwards compatibility as some weird script may rely upon such errors to, for example, detect when a root has not already been created.

@serhiy-storchaka

«no default root window» is correct. There is no yet default root window required by the function. After you create it, explicitly or implicitly, you could use that function.

It could be odd if image_type() will successfully return a result with a side effect of popping up a window.

@shippo16




Copy link

First: thank you!

I’m not saying he ain’t! More so, I greatly appreciate everyone’s time and effort. But I’m discussing the implementation here, not somebody’s work.

An object gets initialized. The object’s constructor accepts a «master» optional parameter (e.g. Variable.__init__). So, every time:
— «master» is None
and
— _support_default_root is True
a default root must be instantiated. A master is optional, and when it’s not given and _support_default_root switch is on, a default root should be supplied. That’s the whole point of _support_default_root after all.

My understanding of the module is not as deep as yours’, but getboolean(), mainloop() and image_types() shouldn’t be affected.

«Too early to create image: no default root window»: Why isn’t there? When _support_default_root is on.

Again, I can see that:

«no default root window» is correct

:But why is there no default window? Support default root is on, right?

There is no yet default root window required by the function.

:A default root is required when you instantiate an Image without a «master». It’s not required as an argument, but it is required for the operation of Image.
I’m suggesting something like:

Best Wishes
Ivo Shipkaliev

@serhiy-storchaka

@serhiy-storchaka

@serhiy-storchaka

@serhiy-storchaka

How to not display the empty root window when creating it

def hide(root):
    root.withdraw()
def show(root):
    root.update()
    root.deiconify()

When you center the root window its size is

(1, 1)

, you should give window size to

center method

.


lambda

is not needed here, use

command=root.destroy

.

import Tkinter as tk
def center(win, width, height):
  win.update_idletasks()
  frm_width = win.winfo_rootx() - win.winfo_x()
  win_width = width + 2 * frm_width
  titlebar_height = win.winfo_rooty() - win.winfo_y()
  win_height = height + titlebar_height + frm_width
  x = win.winfo_screenwidth() // 2 - win_width // 2
  y = win.winfo_screenheight() // 2 - win_height // 2
  win.geometry('{}x{}+{}+{}'.format(width, height, x, y))
def show(root):
    root.update()
    root.deiconify()
def hide(root):
    root.withdraw()
def showDialog():
  print "tkinter"
  root = tk.Tk()
  hide(root)
  root.title("Say Hello")
  label = tk.Label(root, text="Hello World")
  label.pack(side="top", fill="both", expand=True, padx=20, pady=20)
  button = tk.Button(root, text="OK", command=root.destroy)
  button.pack(side="bottom", fill="none", expand=True, padx=10, pady=10)
  center(root, width=200, height=200)
  show(root)
  root.mainloop()
showDialog()

In order to get the information about the widgets, tkinter provides a set of methods that can be used to test the widgets in an application. In order to get the list of all the child widgets, we can use the

winfo_children()

method.

Example

In this example, we have defined some widgets in a frame and by using the

winfo_children()

method, we will print the list containing the names of all the widgets.

#Import tkinter library
from tkinter import *
#Create an instance of tkinter frame
win = Tk()
#Set the geometry
win.geometry("750x200")
#Create a frame
frame= Frame(win)
#Create label, button widgets
Label(frame, text= "Top Level Text", font= ('Helvetica 20 bold')).pack(pady=20)
Button(frame, text= "Left").pack(side=LEFT)
Button(frame, text= "Right").pack(side= RIGHT)
Button(frame, text= "Center").pack(side= BOTTOM)
frame.pack()
#Print the List of all Child widget Information
print(frame.winfo_children())
win.mainloop()

Output

Executing the above code will display a window with a label and three buttons,

On the console, it will print the list of all the widgets defined in frame widget.

[<tkinter.Label object .!frame.!label>, <tkinter.Button object .!frame.!button>, <tkinter.Button object .!frame.!button2>, <tkinter.Button object .!frame.!button3>]

How to create a window tkinter Code Example, Get code examples like «how to create a window tkinter» instantly right from your google search results with the Grepper Chrome Extension.

Creating the Root Window

Once you understand what the root window is and why it is important, you can start to create the root window in your code. Depending on the language that you are coding in, there are different ways to create the root window. In most cases, the code will require you to create a graphical window that will contain the code. You can either do this manually or you can use a library to help you create the window. If you choose to use a library, you need to make sure that the window is properly configured so that the code can be executed properly.

Too early to create image

(see Nesi’s comment)

1 ответ

Эта ошибка означает именно то, что она говорит. Вы не можете вызвать mainloop, пока не создадите корневое окно, и вы никогда не создадите никаких виджетов.

Ваш код должен выглядеть так:

if __name__ == '__main__':
    app = App()
    app.mainloop()

3 Окт 2021 в 01:52

Understanding the Root Window

The root window is a graphical representation of the code that is being written. It can be thought of as the window that your code will be displayed in. The root window contains the code, along with any variables that have been created. When the code is written, the root window should be present in order for the code to execute properly. If the root window is not present, then the code will not be able to execute properly and the error will be thrown.

1 ответ

Почему необходимо объявлять корневое окно для создания образа?

Потому что лежащий в основе интерпретатор tcl/tk должен быть инициализирован, прежде чем вы сможете создавать образы, и именно создание корневого окна выполняет инициализацию.

Это можно обойти

Нет. Вы должны создать корневое окно, прежде чем сможете создавать изображения с помощью tkinter.

11 Авг 2021 в 18:59

Analyzing the Error

The first step in resolving the RuntimeError is to analyze the error message. The message states that there is an issue with the creation of a variable, and that the default root window is not present. This means that the code is trying to create a variable, but the root window is not present. To resolve this issue, you need to understand what the root window is and how it is used in your code.

Testing the Code

After the code has been compiled, it is important to test it to make sure that it is working correctly. This can be done by running the code and checking for any errors. If any errors are found, you can then go back and fix them. Once the code is working correctly, you can then start using it in your program.

Compiling the Code

Once the variables have been created, you can then start to compile the code. This involves using a compiler to check the code for any errors and to ensure that it is properly written. Depending on the language that you are coding in, the compiler may be different. Once the code is compiled, you should be able to execute it without any errors.

Using an Alternative Solution

If you are still having issues with the RuntimeError, then you may want to consider using an alternative solution. One of the most popular alternatives is to use a different language that does not require a root window. Python, for example, is a language that does not require a root window. This can be a great solution if you are having trouble with the RuntimeError and you do not want to spend time debugging the code.

1 ответ

Используйте что-то вроде:

import cv2
import numpy as np
from tkinter import *
from PIL import ImageTk, Image

def refresh_image_loop():
    if cap:
        img = cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2RGB)
        tk_img = ImageTk.PhotoImage(image=Image.fromarray(img))
        label2["image"] = tk_img
        label2.tk_img = tk_img
        root.after(100, refresh_image_loop) # After 100 ms run `refresh_image` again
    else:
        pass

root1 = Tk()

root = Toplevel()
root.title("Camera v1.0")
root.configure(bg="black")

label = Label(root, text="Camera v1.0", font=("times new roman", "15", "bold"),bg="black", fg="goldenrod2")
label.pack(side=TOP, fill=BOTH)

frame = Frame(root, bg="black")
frame.pack()

label2 = Label(frame, bg="red")
label2.pack()

btn_verify = Button(frame,text = "Take a Snapshot", font=("times new roman", "11", "bold"), activebackground='red', bg="#bf80ff", fg="#000080", width=15)
btn_verify.pack(side=BOTTOM, expand=False)

cap = cv2.VideoCapture(0)

refresh_image_loop()
root.mainloop()

Он использует цикл .after. Когда окно закрывается, он автоматически отменяет следующий скрипт .after. Сценарий .after сообщает tkinter вызвать refresh_image_loop через 100 мс, что составляет 0,1 секунды.

27 Апр 2021 в 10:19

Conclusion

Video How to Pass Data between Multiple Windows in Tkinter
Source: CHANNET YOUTUBE CodersLegacy

How to Resolve RuntimeError: Too Early To Create Variable: No Default Root Window?

  1. Verify the configuration settings for the window.
  2. Check for any conflicting settings.
  3. Make sure there is a valid root window.
  4. Update the window library if needed.
  5. Check for any syntax errors.

Variable. __init__ raises obscure AttributeError

shippo16 opened this issue

Dec 13, 2020

· 18 comments

@serhiy-storchaka

Оцените статью
Master Hi-technology
Добавить комментарий