What's wrong with this tkinter program?

user9920858
import random
import time
from tkinter import *    

root = Tk()

x = ""

lab = Label(root,text = x)
lab.pack()

root.mainloop()

def randomno():
    while (1):
        y = random.randint(1, 100)
        y = StringVar()
        x = y.get()
        lab["text"] = x
        #root.update_idletasks()
        time.sleep(2)

randomno()

Error:

Traceback (most recent call last):   File
   "C:/Users/Acer/PycharmProjects/unseen/tp.py", line 26, in <module>
       randomno()   File "C:/Users/Acer/PycharmProjects/unseen/tp.py", line 20, in randomno
       y = StringVar()   File "C:\Users\Acer\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py",
   line 480, in __init__
       Variable.__init__(self, master, value, name)   File "C:\Users\Acer\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py",
   line 317, in __init__
       self._root = master._root() AttributeError: 'NoneType' object has no attribute '_root'
martineau

Here's the common way to do what you want in tkinter:

import random
import time
import tkinter as tk

DELAY = 2000  # milliseconds (thousandth of a second)

def randomno():
    x = random.randint(1, 100)
    lab["text"] = x
    #time.sleep(2)  # Don't call this in a tkinter program!
    root.after(DELAY, randomno)  # Call this function again after DELAY ms.


root = tk.Tk()

lab = tk.Label(root, text="")
lab.pack()

randomno()  # Starts periodic calling of itself.
root.mainloop()

You don't need to use a StringVar and can just assign the new random value in the randomno() function.

You shouldn't call time.sleep() in a tkinter application. Use the universal widget method after() instead. Notice how in the code above how randomno() calls root.after() to arrange for itself to be called again later.

That's how to do something periodically in a tkinter program, and this approach will keep the GUI running not "hang" when sleep() is called.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related