Working with a GUI without using OOP - python

from tkinter import *
root = Tk()
root.title("Button Counter without OOP")
root.geometry("200x85")
app = Frame(root)
app.grid()
bttn = Button(app)
bttn["text"] = "Total Clicks: 0"
bttn.grid()
bttn_clicks = 0
while True:
if bttn:
bttn_clicks += 1
bttn["text"] = "Total Clicks: " + str(bttn_clicks)
bttn.grid()
I can't seem to get this to work. I want the button to count the clicks without using OOP to make this happen.

You need to define a callback function that will called when button is clicked, and bind it using command option of the Button object.
from tkinter import *
bttn_clicks = 0
def on_button_click():
global bttn_clicks
bttn_clicks += 1
bttn["text"] = "Total Clicks: " + str(bttn_clicks)
root = Tk()
root.title("Button Counter without OOP")
root.geometry("200x85")
app = Frame(root)
app.grid()
bttn = Button(app, command=on_button_click) # <---------
bttn["text"] = "Total Clicks: 0"
bttn.grid()
root.mainloop()

Related

How to stop tkinter script until button is pressed

I am trying to make a tkinter script that won't cycle to the next text until a button is pressed
import tkinter as tk
from tkinter import *
window = tk.Tk()
window.geometry("300x300")
TabNum = ["1","2","3"]
TabNumInt = 0
Text = tk.Label(text = ("Page number" + TabNum[TabNumInt]))
Text.pack()
def continuefunct():
global Running
TabNumInt =+ 1
Continuebtn = Button(window, text = 'Continue', bd = '5', command = continuefunct()).pack()
tk.mainloop()
I want this to "print page number [1]" and for the number to increase everytime you press the button until you get to 3. (I know I could have while while TabNumInt =< len(TabNum) but this is just a proof of concept).
Any help would be appreciated :)
There are few issues in your code:
command = continuefunct() will execute the function immediately without clicking the button. Also nothing will be performed when the button is clicked later.
need to declare TabNumInt as global variable inside the function
TabNumInt =+ 1 should be TabNumInt += 1 instead
need to update text of the label inside the function
Below is the modified code:
import tkinter as tk
window = tk.Tk()
window.geometry("300x300")
TabNum = ["1", "2", "3"]
TabNumInt = 0
Text = tk.Label(window, text="Page number "+TabNum[TabNumInt])
Text.pack()
def continuefunct():
global TabNumInt
if TabNumInt < len(TabNum)-1:
TabNumInt += 1
Text.config(text="Page number "+TabNum[TabNumInt])
tk.Button(window, text='Continue', bd='5', command=continuefunct).pack()
window.mainloop()

tkinter freezes due to after() method

The problem is the .after() method inside the 'get_content' function. The delay freezes the whole program. I tried solving it with threading but I can't figure it out. I tried a lot of variations. I will just post the code with the last one! Any suggestions? (The code still needs some fixes here and there but the freezing issue is really annoying and I want to get rid of this first)
import random
import tkinter as tk
from sentences import sentences
import threading
from PIL import ImageTk, Image
root = tk.Tk()
root.title("Speed typing test")
root.geometry('700x700')
# Dynamic labels
entry_text = tk.StringVar()
seconds = tk.IntVar()
# Stopwatch
def seconds_counter(*args):
if not entry_text.get():
seconds.set(0)
else:
counter = 0
while counter < 100:
counter += 1
root.update()
root.after(1000)
seconds.set(counter)
global total_time
total_time = counter
if entry_text.get() == sentence:
final = (len(entry.get()) / 5) / (0.1 * total_time)
final_lbl = tk.Label(root, text=f"WPM: {final}")
final_lbl.pack()
entry.delete(0, tk.END)
seconds.set(0)
word_list = sentence.split(' ')
total_words = len(word_list)
total_words_lbl = tk.Label(root, text=f'Total words: {total_words}')
total_words_lbl.pack()
counter = 0
break
x = threading.Thread(target=seconds_counter)
x.start()
sentence = random.choice(sentences)
sentence = sentence.strip('.')
# Create widgets
logo = ImageTk.PhotoImage(Image.open('images/logo.png'))
logo_lbl = tk.Label(image=logo)
sentence_lbl = tk.Label(root, text=sentence)
entry = tk.Entry(root, width=500, textvariable=entry_text)
seconds_lbl = tk.Label(root, textvariable=seconds)
# Place widgets
logo_lbl.pack()
sentence_lbl.pack()
entry.pack()
seconds_lbl.pack()
entry_text.trace('w', seconds_counter)
def stop():
root.destroy()
# command=quit freezes for some reason
btn_quit = tk.Button(root, text='Quit', command=stop)
btn_quit.pack()
root.mainloop()

How do I create a +1 button in tkinter

**I am writing a baseball counting program. I have a label for walks and strikeouts. To the side of those labels I have buttons with the text "+1". I want the buttons to be able to change and print the number of walks and strikeouts every time I click the +1 buttons. I just need some ideas to help get started. Here is my code for clarification: **
import tkinter as tk
from tkinter.constants import COMMAND, X
global walk_counter
walk_counter = 0
global strikeout_counter
strikeout_counter = 0
def main(): # This is the main function
root = tk.Tk()
frame = tk.Frame(root)
frame.master.title("Random Title")
frame.pack(padx=4, pady=3, fill=tk.BOTH, expand=1)
populate_boxes(frame)
root.mainloop()
def populate_boxes(frame):
walks_label = tk.Label(frame, text="BB:")
walks_entry = tk.Label(frame, width=4)
walks_button = tk.Button(frame,text="+1")
strikeouts_label = tk.Label(frame,text="Strikeouts:")
strikeouts_entry = tk.Label(frame,width=4)
strikeouts_button = tk.Button(frame,text="+1")
walks_label.place(x=200,y=500)
walks_entry.place(x=250,y=500)
walks_button.place(x=300,y=500)
strikeouts_label.place(x=400,y=500)
strikeouts_entry.place(x=450,y=500)
strikeouts_button.place(x=500,y=500)
def add_more_walks():
global walk_counter
walk_counter += 1
walks_entry.config(text = walk_counter)
add_more_walks()
main()

How to make a button create a label and shortly after that hide in tkinter

My code:
def Click():
global output
output = StringVar()
output = random.randint(1, 6)
global outputL
outputL = Label(root, text = f"The number is... {output}")
outputL.pack()
output = 0
How do I make it hide the label after that?
Use after method and config method
(TIP) Don't create a widgets(Labels, Buttons, etc...) inside a function. Use config method to update your widgets
from tkinter import *
import random
root = Tk()
def Remove_Output():
outputL.pack_forget()
def click():
global output
output = StringVar()
output = random.randint(1, 6)
outputL.config(text=f"The number is... {output}")
outputL.pack()
output = 0
root.after(1000, Remove_Output)
btn = Button(root, text="Click",command=click)
btn.pack()
outputL = Label(root, text = "")
root.mainloop()

Label with textvariable not showing up

Label "totalresults" in window "root2" is not showing up. I would like to that text label to update every time button is pressed in first window and calculate the amount of those button presses.
#create the window
root = Tk()
root2 = Tk()
#probability calculations
totalrolls = tk.StringVar()
amountofrolls = 0
#update numbers in gui
def add_num():
global amountofrolls
amountofrolls += 1
totalrolls.set("Amount of rolls made in total: " +str(amountofrolls))
#button functions
def button_press():
add_num()
#string variable
totalrolls.set("Amount of rolls made in total: " + str(amountofrolls))
#modify second window
todennäköisyys = Label(root2, text="The quantity of results:")
totalresults = Label (root2, textvariable=totalrolls)
todennäköisyys.pack()
totalresults.pack()
#kick off the event loop
root.mainloop()
root2.mainloop()
I am not getting any errors or anything the second window just dosent show the label.
You should not start more than one instance of Tk(). Use Toplevel() instead. See example:
from tkinter import *
root = Tk() # create the window
display = Toplevel(root)
#probability calculations
totalrolls = StringVar()
amountofrolls = 0
def add_num(): # update numbers in gui
global amountofrolls
amountofrolls += 1
totalrolls.set("Amount of rolls made in total: " + str(amountofrolls))
def button_press(): # button functions
add_num()
#string variable
totalrolls.set("Amount of rolls made in total: " + str(amountofrolls))
#modify second window
todennäköisyys = Label(display, text="The quantity of results:")
totalresults = Label (display, textvariable=totalrolls)
todennäköisyys.pack()
totalresults.pack()
# Create button in root window
Button(root, text='Increase number', command=add_num).pack()
#kick off the event loop
root.mainloop()

Categories

Resources