How do I fix "name is not defined error" (tkinter) - python

I'm trying to make a stopwatch app with Tkinter, but now I have some trouble. Somewhy, I'm receiving the following error:
name 'label13' is not defined. line 177, in countdown
label13.config(text = count)
I have no idea why this error message pops up. I really appreciate it if you can help me.
Here is my code:
from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage
from tkinter import *
window = Tk()
window.geometry("703x981")
window.configure(bg = "#FFFFFF")
def countdown(count):
#change text in label
label13.config(text = count)
if count > 0:
#call countdown again after 1000ms (1s)
window.after(1000, countdown, count-1)
countdown(120)
label13 = Label(window, font = "Courier 40 bold", bg="white", fg="black")
label13.place(x =29, y=300)
window.resizable(False, False)
window.mainloop()

Because label13 should defined before calling countdown(120) as shown below.
from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage
from tkinter import *
window = Tk()
window.geometry("703x981")
window.configure(bg = "#FFFFFF")
window.resizable(False, False)
label13 = Label(window, font = "Courier 40 bold", bg="white", fg="black")
label13.place(x =29, y=300)
def countdown(count):
#change text in label
label13.config(text = count)
if count > 0:
#call countdown again after 1000ms (1s)
window.after(1000, countdown, count-1)
countdown(120)
window.mainloop()

Related

How can i change content inside of a window after pressing a button in tkinter?

I actually found a solution for this but they used an entirely different way of making windows/buttons and i can't figure out how to use it.
Please tell me if there's a way to make this happen with my code.
The code for my window and its content is as below
from tkinter import *
title = 'zromber'
window = Tk()
window.geometry("800x400")
def play():
print('welcome')
window.destroy()
def save():
print('yes')
playbutton = Button(window, text='play')
playbutton.config(command=play)
playbutton.config(font=('none', 50, 'bold'))
testlabel = Label(window, text=title)
testlabel.config(font=('Ink Free', 50))
testlabel.pack()
playbutton.pack()
savebutton = Button(window, text='save')
savebutton.config(command=save)
savebutton.config(font=('none', 50, 'bold'))
savebutton.pack()
window.mainloop()
from tkinter import *
title = 'zromber'
window = Tk()
window.geometry("800x400")
my_text = "Hi, I'm a the new label"
def play():
#use label.config(text="new text") to change text
my_label.config(text=my_text+" and I'm from play")
def save():
my_label.config(text=my_text+" and I'm from save")
playbutton = Button(window, text='play')
playbutton.config(command=play)
playbutton.config(font=('none', 50, 'bold'))
testlabel = Label(window, text=title)
testlabel.config(font=('Ink Free', 50))
testlabel.pack()
playbutton.pack()
savebutton = Button(window, text='save')
savebutton.config(command=save)
savebutton.config(font=('none', 50, 'bold'))
savebutton. pack()
#Define the label
my_label = Label(window, text="THIS IS A LABEL")
my_label.config(font=('none', 10, 'bold'))
my_label.pack()
window.mainloop()
Here I've created a new label called my_label and when the play button calls for the play() function, i've used label.config(text="new text") to change text.
You can run the sample code above to get your results.

Tkinter center Label in the GUI

import tkinter as tk
from tkinter import *
HEIGHT = 600
WIDTH = 600
root = tk.Tk()
def button_event1():
import ThreePlayers
print(ThreePlayers)
def button_event2():
import TwoPlayersGame
print(TwoPlayersGame)
def button_event3():
print("")
def button_event4():
print("")
def button_event5():
quit()
root = Tk()
root.title('Connect 4 Game')
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()
L = Label(root, text="Welcome to 3P Connect 4!!!",font=("Ariel",20,"bold", "underline"))
L.config(anchor=CENTER)
L.pack()
button = tk.Button(root, text="3 Player Game", command=button_event1)
button.pack()
button = tk.Button(root, text="2 Player Game", command=button_event2)
button.pack()
button = tk.Button(root, text="1 Player Game", command=button_event3)
button.pack()
button = tk.Button(root, text="Options", command=button_event4)
button.pack()
button = tk.Button(root, text="QUIT", command=button_event5)
button.pack()
root.mainloop()
Above is my Code for a Tkinter GUI but I want the have the label at the center of the root/window how do I do that? Currently its sitting on top of the buttons everything else is fine the button events and such works
In my opinion, you should have used place or grid instead of pack. Because pack only gives few alignment options.
otherwise, maybe divide the main window into two frames then pack the label at the top of the lower frame
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
L = Label(root, text="Welcome to 3P Connect 4!!!",font=("Ariel",20,"bold", "underline"))
L.pack(side = TOP)
I wish this helps. but you should use grid for better alignment or place.
You can use the following commands to place the label in the center
L = Label(root, text="Welcome to 3P Connect 4!!!",font=("Ariel",20,"bold", "underline"))
# L.config(anchor=CENTER)
# L.pack()
L.place(x=HEIGHT/2, y=WIDTH/2, anchor="center")
Similarly, you can also use button.place(x=100, y=25) for buttons
REF: Tkinter: Center label in frame of fixed size?

Displaying time in tkinter label

I am trying to get the current time to show and update every second in a tkinter label.
Im assuming that i am doing this completely wrong. Im rather new to this and trying to work through it bit by bit.
from tkinter import *
import sys
import time
#function to close window when ESC is pressed
def close(event):
sys.exit()
def curtime():
while 1==1:
current_time = time.strftime('%H:%M:%S')
print(current_time)
time.sleep(1)
#Main System
window = Tk()
window.state('zoomed')
window.configure(bg='#3a3a3a')
#Frames
top_frame = Frame(window)
top_frame.pack(side=TOP)
bottom_frame = Frame(window)
bottom_frame.pack(side=BOTTOM)
#Labels
header_label = Label(top_frame, text="SARA", background='#3a3a3a', fg='#ffffff', font=("calibri", 50))
header_label.pack(side=LEFT)
header_label2 = Label(top_frame, textvariable = curtime(), background='#3a3a3a', fg='#ffffff', font=("calibri", 50))
header_label2.pack(side=LEFT)
#on press ESC window closes
window.bind('<Escape>', close)
window.mainloop()
#function to get timer to calculate
def timer():
timer_tick = strftime("%I:%M:%S")
time_label.configure(text=timer_tick)
time_label.after(1000, timer)
time_label = Label(top_frame, background='#3a3a3a', fg='#ffffff', font=("calibri", 50))
time_label.pack(side=LEFT)
#if statement which constantly returns true to make the timer refresh and tick
if __name__ == "__main__":
timer()

How to make a Tkinter window not resizable?

I need a Python script that uses the Tkinter module to create a static (not resizable) window.
I have a pretty simple Tkinter script but I don't want it to be resizable. How do I prevent a Tkinter window from being resizable? I honestly don't know what to do.
This is my script:
from tkinter import *
import ctypes, os
def callback():
active.set(False)
quitButton.destroy()
JustGo = Button(root, text=" Keep Going!", command= lambda: KeepGoing())
JustGo.pack()
JustGo.place(x=150, y=110)
#root.destroy() # Uncomment this to close the window
def sleep():
if not active.get(): return
root.after(1000, sleep)
timeLeft.set(timeLeft.get()-1)
timeOutLabel['text'] = "Time Left: " + str(timeLeft.get()) #Update the label
if timeLeft.get() == 0: #sleep if timeLeft = 0
os.system("Powercfg -H OFF")
os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0")
def KeepGoing():
active.set(True)
sleep()
quitButton1 = Button(root, text="do not sleep!", command=callback)
quitButton1.pack()
quitButton1.place(x=150, y=110)
root = Tk()
root.geometry("400x268")
root.title("Alert")
root.configure(background='light blue')
timeLeft = IntVar()
timeLeft.set(10) # Time in seconds until shutdown
active = BooleanVar()
active.set(True) # Something to show us that countdown is still going.
label = Label(root, text="ALERT this device will go to sleep soon!", fg="red")
label.config(font=("Courier", 12))
label.configure(background='light blue')
label.pack()
timeOutLabel = Label(root, text = 'Time left: ' + str(timeLeft.get()), background='light blue') # Label to show how much time we have left.
timeOutLabel.pack()
quitButton = Button(root, text="do not sleep!", command=callback)
quitButton.pack()
quitButton.place(x=150, y=110)
root.after(0, sleep)
root.mainloop()
The resizable method on the root window takes two boolean parameters to describe whether the window is resizable in the X and Y direction. To make it completely fixed in size, set both parameters to False:
root.resizable(False, False)

How to make a Label appear then disappear after a certain amount of time in python tkinter

I would like for a cant afford label to appear then after a second disappear when i push a button to buy something. It seems like the time.sleep(1) is making it not work properly. This is done on python tkinter.
def buttonpressed():
Label.place(x = 500, y = 500 #where i want the label to appear
time.sleep(1)
Label.place(x = 10000, y = 10000) #moving it away where i wont be able to see it
You can't use sleep because it stops mainloop
You can use root.after(time_in_milliseconds, function_name) to run function
Example
import tkinter as tk
def button_pressed():
# put text
label['text'] = "Hello World!"
# run clear_label after 2000ms (2s)
root.after(2000, clear_label)
def clear_label():
# remove text
label['text'] = ""
root = tk.Tk()
label = tk.Label(root) # empty label for text
label.pack()
button = tk.Button(root, text="Press Button", command=button_pressed)
button.pack()
root.mainloop()
If you have to create and remove label then use label.destroy()
import tkinter as tk
def button_pressed():
label = tk.Label(root, text="Hello World!")
label.pack()
root.after(2000, destroy_widget, label) # label as argument for destroy_widget
def destroy_widget(widget):
widget.destroy()
root = tk.Tk()
button = tk.Button(root, text="Press Button", command=button_pressed)
button.pack()
root.mainloop()
And shorter version without destroy_widget
import tkinter as tk
def button_pressed():
label = tk.Label(root, text="Hello World!")
label.pack()
root.after(2000, label.destroy)
root = tk.Tk()
button = tk.Button(root, text="Press Button", command=button_pressed)
button.pack()
root.mainloop()
Press button many times to see many labels which disappear after 2s.
You can use after() to set up a callback after a specified interval. In the callback function clear the label with pack_forget() (or grid_forget() if you're using grid). This is better than setting the label's text attribute to an empty string because that causes widgets to be resized, which might not be what you want. Here's an example:
import Tkinter as tk
class App():
def __init__(self):
self.root = tk.Tk()
self.label = tk.Label(text='I am a label')
self.label.place(x=0, y=0)
self.label.after(1000, self.clear_label) # 1000ms
self.root.mainloop()
def clear_label(self):
print "clear_label"
self.label.place_forget()
app=App()
Another option is to use self.label.destroy() to destroy the widget, however, pack_forget() allows you to display the label again by calling pack() on the widget again.
# I made it through calling 2 functions:
from tkinter import *
root = Tk()
root.geometry('400x200') # width by height
def one_text():
label['text'] = "Look around"
root.after(1000, another_text)
def another_text():
label['text'] = "and smile"
root.after(1000, one_text)
label= Label(root ,font=('Helvetica', 14), fg='black', bg='white')
label.pack()
one_text()
root.mainloop()

Categories

Resources