Home > Blockchain >  What is this bizarre tkinter error in my timer?
What is this bizarre tkinter error in my timer?

Time:07-24

I decided to make a tkinter timer but am receiving a very strange error.
Here is the code and the error:

import tkinter as tk
import time

window = tk.Tk()
window.title("Hello wold")
window.geometry("300x300")
timer = int(input("time in seconds"))

for i in range(timer):
  timer -= 1
  print(timer)
  time.sleep(1)
  hello = tk.Label("timer")
  hello.pack()
  tk.mainloop()

The error:

Traceback (most recent call last):
  File "main.py", line 14, in <module>
    hello = tk.Label("timer")
  File "/usr/lib/python3.8/tkinter/__init__.py", line 3143, in __init__
    Widget.__init__(self, master, 'label', cnf, kw)
  File "/usr/lib/python3.8/tkinter/__init__.py", line 2561, in __init__
    BaseWidget._setup(self, master, cnf)
  File "/usr/lib/python3.8/tkinter/__init__.py", line 2530, in _setup
    self.tk = master.tk
AttributeError: 'str' object has no attribute 'tk'

CodePudding user response:

To change the text of a label you need to define the text property:

hello = tk.Label(text="timer")

This will set the text of the label to "timer", but if you want to set it as the variable you previously declared (called timer) - simply remove the quotation marks.

hello = tk.Label(text=timer)

This will set the text of the label to whatever the variable 'timer' is equal to. However you also need to set the window, which leaves the final code to this:

hello = tk.Label(window, text=timer)

CodePudding user response:

  • I added tk.StringVar in line 16.
  • I added textvariable=string_variable in line 17
  • tk.mainloop was relocated outside of the loop block in line 20

Here is code:

import tkinter as tk
import time

window = tk.Tk()
window.title("Hello wold") 
window.geometry("300x300")
 

timer = int(input("time in seconds"))

for i in range(timer):
  timer -= 1
  print(timer)
  time.sleep(1)

  string_variable = tk.StringVar(window, timer)   
  hello = tk.Label(window, textvariable=string_variable)
  hello.pack()
 
tk.mainloop()

Output result:

enter image description here

  • Related