How do I update this Text Box's text in Tkinter? - python

So I am making a stopwatch in python with tkinter, I have the loop for updating the time working, but I have it so the loop clears the text box, and then updates the text box with the new number.
Although it doesnt work, for some reason it just doesnt clear it, it just keeps adding numbers to the box.
Here is the code that I have used, if someone would be able to have a look at this for me I would appriciate it a lot :)
import time
from tkinter import *
root = Tk()
root.title("StopWatch")
#textbox for the screen
screen = Text(root, height = 1, width = 20, bd=10)
screen.grid(row=0, column=0)
#Active variable
global stopwatch_active
stopwatch_active = False
stop_time = 0
stop_minutes = 0
#command for starting the stopwatch
def start_com():
stop_btn.config(state=NORMAL)
stopwatch_active = True
start_btn.config(state=DISABLED)
global stop_time
stop_time += 1
screen.insert(END, stop_time)
root.after(1000, start_com)
#button for starting the stopwatch
start_btn = Button(root, text = "Start", width = 10, bd = 5, command = start_com)
start_btn.grid(row=1, column=0, sticky=W)
#button for stopping the stopwatch
stop_btn = Button(root, text = "Stop", width = 10, bd = 5)
stop_btn.grid(row=1, column=0, sticky=E)
stop_btn.config(state=DISABLED)

Add:
screen.delete("1.0", END)
Before you do:
screen.insert(END, stop_time)
This will clear all the text from the text box. Effbot has more information if your interested. This will produce something similar to:

Related

Python, tkinter How to allow clicks through app?

I am new to coding and python. I use tkinter to make an app and want to know how to allow your clicks to affect the apps and stuff behind my app without interacting with my app. My app is designed to turn the screen pink by adding a transparent overlay. I want to make the overlay visible but not affecting the other apps or pc.(https://i.stack.imgur.com/UW4tR.png)](https://i.stack.imgur.com/UW4tR.png)
I have tried looking at other posts and found solutions but none worked quite right. This is my current code. How it is expected to work is the overlay is there but you can interact with everything behind it as if the app was not there.
import tkinter as tk
from tkinter import *
import time
from tkinter import ttk
from tkinter import messagebox
win = tk.Tk()
win.title("Pink-Out")
win.geometry("1900x1000")
win.attributes('-alpha',1)
win.configure(bg='black')
sec = StringVar()
Entry(win, textvariable=sec, width = 2, font = 'Helvetica 14').place(x=1720, y=900)
sec.set('00')
mins= StringVar()
Entry(win, textvariable = mins, width =2, font = 'Helvetica 14').place(x=1680, y=900)
mins.set('00')
hrs= StringVar()
Entry(win, textvariable = hrs, width =2, font = 'Helvetica 14').place(x=1640, y=900)
hrs.set('00')
def pink():
command = win.configure(bg='#FF007F')
command = win.attributes('-fullscreen', True)
command = win.attributes('-alpha', 0.10, '-topmost', 1)
messagebox.showinfo("", "Remeber to look away from your screen every 20 min to protect your eyes.")
# hide the button
for i in range(1,100):
times = int(hrs.get())*3600+ int(mins.get())*60 + int(sec.get())
while times > -1:
minute,second = (times // 60 , times % 60)
hour =0
if minute > 60:
hour , minute = (minute // 60 , minute % 60)
sec.set(second)
mins.set(minute)
hrs.set(hour)
#Update the time
win.update()
time.sleep(1)
if(times == 0):
sec.set('00')
mins.set('20')
hrs.set('00')
messagebox.showinfo("", "Take a break")
times -= 1
b1 = tk.Button(win, text='START', bd ='2', bg = 'IndianRed1',font =('Helvetica bold',10), command = pink).place(x=2667, y=925)
win.bind('<Return>', lambda event:pink())
win.mainloop()
This is not an answer. I will delete it sooner.
Your Entry and Button is out of window. I am not going to try this.
In Line 8, I changed window size.
win.geometry("640x480")
In line 13,. Change this: Entry(win, textvariable=sec, width = 2, font = In line 13, 'Helvetica 14').place(x=20, y=90)
In line 16. Change this: Entry(win, textvariable = mins, width =2, font = 'Helvetica 14').place(x=50, y=90)
In line 19. Change this: Entry(win, textvariable = hrs, width =2, font = 'Helvetica 14').place(x=80, y=90)
In Line 50. Change this: b1 = tk.Button(win, text='START', bd ='2', bg = 'IndianRed1',font =('Helvetica bold',10), command = pink).place(x=26, y=25)
Result:

after_cancel doesn't work in python tkinter

I made a simple countdown in my trivia game and every time that I go to the next slide it doesn't cancel the previous countdown timer and overlaps with the previous one.
I searched about that on the web and found the after_cancel function that cancels the timer after I go to the next slide and then I recreate it. But it still overlaps even after I added this function.
I think that I didn't give the after_cancel the correct arguments.
from tkinter import *
window = Tk()
window.attributes('-fullscreen',True)
WaitState = StringVar()
count = 10
button_label = StringVar()
def clear():
WaitState.set(1)
for widgets in window.winfo_children():
widgets.destroy()
def clear_time():
clear()
time_up_label = Label(
window,
text="Time is up",
bg = "#6378ff",
fg="#000000",
font=("Arial", 100,"bold"))
time_up_label.place(relx = 0.5,rely = 0.5,anchor = 'center')
continue_but = Button(
window,
text="Continue",
font=("Knewave",25,"bold"),
bg="#942222",
width=11,
height=5,
command=clear)
continue_but.place(relx = 1.0,rely = 1.0,anchor =SE)
continue_but.wait_variable(WaitState)
def button_countdown(i, label):
if i > 0:
i -= 1
label.set(i)
window.after_id = window.after(1000, lambda: button_countdown(i, label))
else:
window.after_cancel(window.after_id)
clear_time()
for index in range(5):
continue_but = Button(
window,
text="Continue",
font=("Knewave",25,"bold"),
bg="#942222",
width=11,
height=5,
command=clear)
continue_but.place(relx = 1.0,rely = 1.0,anchor =SE)
button_label.set(count)
timer_label = Label(
window,
textvariable=button_label,
bg="#6378ff",
fg="#ff0000",
font=("Arial",46,"bold"))
timer_label.pack()
button_countdown(count, button_label)
continue_but.wait_variable(WaitState)
window.mainloop()

How to use GUI Tkinter button to increment a number and display it

I'm new to trying out python GUI's and tried tkinter and pyglet, but only through tutorials, in-order-to understand the basic classes and functions. But what I'm currently trying to do is to get a button to increase a number whilst displaying that number at the same time. Somehow, even though the variable number was stated globally as 0, the function to increase it doesn't do anything, it actually produces an error: 'UnboundLocalError: local variable 'number' referenced before assignment'. I have no idea how to correct this.
The tutorials I've seen on both YouTube and as an article, don't talk about how to do this exactly. The article does mention how to change a certain text though, but not a previously created variable (which in my case would be 'number').
from tkinter import *
number = 0
window = Tk()
window.title("Programme")
window.geometry('350x250')
label = Label(window, text=number)
label.grid(column=0,row=0)
def clicked():
number += 1
button = Button(window, text="Push Me", command=clicked)
button.grid(column=1, row=2)
window.mainloop()
Is there any way to do this?
Also I've been looking for how to add time, to handle events and such, through ticks. But everything I find on the internet is about literally displaying a clock on the GUI, which is useless, or at least I don't know how to use it to have a ticking function.
You need to increment the number, like you do, but also update the Label to display the new number:
from tkinter import *
number = 0
window = Tk()
window.title("Programme")
window.geometry('350x250')
label = Label(window, text=number)
label.grid(column=0,row=0)
def clicked():
global number
number += 1
label.config(text=number)
button = Button(window, text="Push Me", command=clicked)
button.grid(column=1, row=2)
window.mainloop()
An easier way to do this is to use tkinter's version of an integer: IntVar. It takes care of the Label updates automatically, but it requires you use get() and set() to work with it.
from tkinter import *
def clicked():
number.set(number.get()+1)
window = Tk()
window.title("Programme")
window.geometry('350x250')
number = IntVar()
label = Label(window, textvariable=number)
label.grid(column=0,row=0)
button = Button(window, text="Push Me", command=clicked)
button.grid(column=1, row=2)
window.mainloop()
Here is my entire code:
from tkinter import *
def up():
number.set(number.get()+1)
def down():
number.set(number.get()-1)
window = Tk()
window.title("Programme")
window.geometry('350x250')
number = IntVar()
frame = Frame(window)
frame.pack()
entry = Entry(frame, textvariable=number, justify='center')
entry.pack(side=LEFT, ipadx=15)
buttonframe = Frame(entry)
buttonframe.pack(side=RIGHT)
buttonup = Button(buttonframe, text="▲", font="none 5", command=up)
buttonup.pack(side=TOP)
buttondown = Button(buttonframe, text="▼", font="none 5", command=down)
buttondown.pack(side=BOTTOM)
window.mainloop()
It looks better for me when the buttons are inside of the entry widget directly.

How to fix my Function so it works in my Tkinter Application (Guessing Game)

Basically, I want to go through answers and check every time if that's correct with a button and then pop it from the list. In another file/code/application it's working when I try to use it on my Gui Application it doesn't iterate and only keeps the first answer right.
I tried multiple things like using Dictionaries and getting the key but it still doesn't iterate over after the Button press.
This is the code that works fine:
while answers == True:
answers = ["Sayajin", "Namek", "Cell", "TournamentOfPower"]
for a in range(4):
s = input()
if s in answers[0]:
print("Richtig")
answers.pop(0)
This is the code that doesnt work:
def check(event):
answers = ["Sayajin", "Namek", "Cell", "TournamentOfPower"]
for a in range(4):
s = entrysaga.get()
if s in answers[0]:
print("Richtig")
answers.pop(0)
Complete Code:
from tkinter import *
import tkinter.messagebox
import time
import random
root = Tk()
#Hint Button
hint = Button(root, text= "Hint")
hint.bind("<Button-1>")
hint.place(x=50, y=20)
#How to Play Button + Info Message how to play
def Howtoplay():
tkinter.messagebox.showinfo("How to play", "To start the game u have
to press the button (Start)\n---------------------------------------------
----------------\n"
""
"Then the Picture will switch
and its going to show u a Character and u have to guess from which Dragon
Ball Saga he is.\n--------------------------------------------------------
-----\n"
"Just type it in the Entry and
press Check after that if u were right the next picture shows up")
info = Button(root, text="How to Play", command=Howtoplay)
info.bind("<Button-1>")
info.place(x=150, y=20)
#textwidget
textwidget = Label(root, text="Entry the DragonBall Saga:")
#entry widget
entrysaga = Entry(root)
#Pictures for guessing the Saga
Sayajin = PhotoImage(file="sayajinsaga.png")
Namek = PhotoImage(file="NamekSaga.png")
Cell = PhotoImage(file="CellSaga.png")
Buu = PhotoImage(file="BuuSaga.png")
TournamentOfPower = PhotoImage(file="TournamentOfPowersaga.png")
#Start function
def start():
labelSagas.config(image=Sayajin)
#define check for pictures
def check(event):
answers = ["Sayajin", "Namek", "Cell", "TournamentOfPower"]
for a in range(4):
s = entrysaga.get()
if s in answers[0]:
print("Richtig")
answers.pop(0)
#button check
buttonsaga = Button(root, text="Check")
buttonsaga.bind("<Button-1>", check)
textwidget.place(x=300, y=170)
entrysaga.place(x=300, y= 200)
buttonsaga.place(x=440, y=195)
#Start Button
start = Button(root, text="Start", command=start)
start.bind("<Button-1")
start.place(x=400, y=20)
# Label with start picture,
startpic = PhotoImage(file="dbzsagas.png")
labelSagas = Label(root, image=startpic)
labelSagas.place(x=25, y=80)
#size of window
root.geometry("500x280")
#window title
root.title("Dragon Ball Saga´s guessing game")
#start of the window
root.mainloop()
My excepted output should be like in the first code that it iterates over and after getting the first answer right ur on to the next one. But the actual result it that stays on the first.
I have moved the widgets which should appear when you press the Start button. They are all in the def start(): function as they would not appear otherwise.
As entrysaga was being called within a different function it could not find the inputted value as the variable is not a global variable. By using global entrysaga it means that it is and can be called from anywhere within the script.
This is how it looks:
from tkinter import *
import tkinter.messagebox
import time
import random
root = Tk()
#Hint Button
hint = Button(root, text= "Hint")
hint.bind("<Button-1>")
hint.place(x=50, y=20)
#How to Play Button + Info Message how to play
def Howtoplay():
tkinter.messagebox.showinfo("How to play", "To start the game u have to press the button (Start)\n--------------------------------------------- ----------------\n"
""
"Then the Picture will switch and its going to show u a Character and u have to guess from which Dragon Ball Saga he is.\n-------------------------------------------------------- -----\n"
"Just type it in the Entry and press Check after that if u were right the next picture shows up")
info = Button(root, text="How to Play", command=Howtoplay)
info.bind("<Button-1>")
info.place(x=150, y=20)
#Pictures for guessing the Saga
Sayajin = PhotoImage(file="sayajinsaga.png")
Namek = PhotoImage(file="NamekSaga.png")
Cell = PhotoImage(file="CellSaga.png")
Buu = PhotoImage(file="BuuSaga.png")
TournamentOfPower = PhotoImage(file="TournamentOfPowersaga.png")
#Start function
def start():
labelSagas.config(image=Sayajin)
global entrysaga
entrysaga = tkinter.Entry(root)
entrysaga.place(x=300, y= 200)
buttonsaga = Button(root, text="Check")
buttonsaga.bind("<Button-1>", check)
buttonsaga.place(x=440, y=195)
textwidget = Label(root, text="Entry the DragonBall Saga:")
textwidget.place(x=300, y=170)
#define check for pictures
def check(event):
answers = ["Sayajin", "Namek", "Cell", "TournamentOfPower"]
for a in range(4):
s = entrysaga.get()
if s in answers[0]:
print("Richtig")
answers.pop(0)
#Start Button
start = Button(root, text="Start", command=start)
start.bind("<Button-1")
start.place(x=400, y=20)
# Label with start picture,
startpic = PhotoImage(file="dbzsagas.png")
labelSagas = Label(root, image=startpic)
labelSagas.place(x=25, y=80)
#size of window
root.geometry("500x280")
#window title
root.title("Dragon Ball Saga´s guessing game")
#start of the window
root.mainloop()
Hope this helps! :)

Why Won't My Button Be Displayed??

#Last one Looses (II)
from tkinter import *
from tkinter import ttk
root = Tk()
#window
root.title("Last one Looses Mark II")
#Counters Entry
counters = StringVar()
countersL = Label(root, text = "How many counters do you want to play with (10-50)")
countersL.pack(side = LEFT)
countersE = Entry(root, textvariable = counters, bd = 5)
countersE.pack(side = RIGHT)
#Function to process this
def countersinput():
no_counters = int(input(counters.get()))
no_counters = int(input(counters.get()))
#Submit Button
countersB = Button(root, text = "Submit", command = countersinput)
countersB.pack(side = BOTTOM)
#Making sure the counters are between 10-50
while no_counters > 50 or no_counters < 10:
Error = Message(root, text="You need to pick between 10 and 50 counters...")
Error.pack()
counters = StringVar()
countersL = Label(root, text = "How many counters do you want to play with (10-50)")
countersL.pack(side = LEFT)
countersE = Entry(root, textvariable = counters, bd = 5)
countersE.pack(side = RIGHT)
def countersinput():
no_counters = int(input(counters.get()))
countersB = Button(root, text = "Submit", command = countersinput)
countersB.pack(side = BOTTOM)
#Sucess Message
Sucess = Message(root, text=("You are playing with",no_counters,"counters"))
root.mainloop()
Whenever I run it in IDLE the tkinter window does not come up and when I run it into the command line (python one...) it displays the window but with no "submit" button.
I'm really confused please help!
First off, do you realize that your GUI program is asking for input from the command line, and that you're doing that before creating the submit button? That's the reason why the submit button is not showing up. If you're writing a GUI program, you should not be trying to read input from the command line.
If you enter a number between 10 and 50 from the terminal, your code should display a window. However, if you enter a number outside that range, nothing will ever show because of the while no_counters ... loop. That loop will run infinitely, preventing any other interaction with the GUI, and preventing any other widgets from showing up.

Categories

Resources