Label with textvariable not showing up - python

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()

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()

How to display a value on Tkinter window from a function every second?

So I'm working on a function does something (turns a motor) every second. For counting the second I use time.sleep(1) because I don't know any other way to wait.
def wash_loop(wash_time):
count = 0
dist = 0
global error_flag
error_flag = 0
while (count < wash_time):
if(count%2==0):#going forward
GPIO.output(Motor_IN1,GPIO.HIGH)
GPIO.output(Motor_IN2,GPIO.LOW)
GPIO.output(Motor_EN,GPIO.HIGH)
print(count)
time.sleep(MOTOR_SLEEP)
else:#going backwards
GPIO.output(Motor_IN1,GPIO.LOW)
GPIO.output(Motor_IN2,GPIO.HIGH)
GPIO.output(Motor_EN,GPIO.HIGH)
print(wash_time - count) #want to display this on a Tkinter window instead
time.sleep(MOTOR_SLEEP)
count+=1
dist = distance_check()
if(dist < CRITICAL_DIS):
error_alert()
break
if(count>=wash_time):
GPIO.output(Motor_EN, GPIO.LOW)
break
The Tkinter function that I'm trying to do this in looks like this:
def wash_window():
#create the main window for GUI control applcation
window2 = TK.Tk()
temp = TK.IntVar()
window2.geometry(WINDOW_GEOMETRY)
window2.title("Wash Cycle ")
#create the frame that will hold instructions
frame0 = TK.Frame(window2)
frame0.pack(side=TK.TOP)
TK.Label(frame0, text="You've selected custom wash cycle").grid(row=0,column=0)
TK.Label(frame0, text="Please select the water temperature for the wash.")\
.grid(row=1,column=0)
frame1 = TK.Frame(window2)
frame1.pack(side=TK.TOP)
temp.get()
hot_button = TK.Radiobutton(frame1, text="HOT", variable=temp, value=1 ).grid(row=0, column=0)
cold_button = TK.Radiobutton(frame1, text="COLD", variable=temp, value=2).grid(row=0,column=1)
warm_button = TK.Radiobutton(frame1, text="WARM", variable=temp, value=3).grid(row=0,column=2)
#create the frame that will hold control entry in the window
frame2 = TK.Frame(window2)
frame2.pack(side=TK.TOP)
TK.Label(frame2, text = "Please enter the time below for the wash cycle").grid(row=0,column=0)
user_entry = TK.Entry(frame2)
user_entry.grid(row=1,column=0)
frame3= TK.Frame(window2)
frame3.pack(side=TK.TOP)
start_button = TK.Button(frame3, text="START", command = lambda: wash_cycle(user_entry,temp)).grid(row=0, column=0)
# stop_button = TK.Button(frame3, text="STOP", command = lambda: wash_cycle(user_entry,temp)).grid(row=0, column=1)
quit_button = TK.Button(frame3, text="QUIT", command = window2.destroy).grid(row=0, column=2)
What I'm trying to do is display the countdown (from the entered time to 0) on this Tkinter window as soon as the person presses start in the window. This is different from using the after() function because I want to show a value from a function which is only executing once, only with the exception that it has a loop.
Thank You!
So what you could do is work with threading.
You Need to:
from threading Import Timer
Then you create a timer
your_timer = Timer(the_seconds_you_want_to_wait, the_function_to_call)
You are calling a function with this and in that function you can display anything in your tkinter window.
What I recommend you to do here is create a Label and then change the properties of it.
For example if you want to show a number on a label:
L1 = Label(root, text="your text here")
L1.pack()
Now if you want to edit that later:
L1.configure(text="your new text here")
your_timer.start()
And at the end of your function you Need to Start the timer in order to the create a cycle or just create a Loop for it.

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()

Python Tkinter Menu System. Unable to get prices totaled and displayed

New to python & I have been tryna to build a small Menu with Tkinter, my idea is when I select an item from the menu the name of it appears in the larger screen and the total of the items selected appears in the smaller screen, my function is called fireFood. I'm currently seeing my prices run on a line instead of being totaled and I've been stuck on this for a couple days, hope someone can point me in the right direction.
rom tkinter import ttk
import tkinter as tk
root = tk.Tk()
root.geometry('500x300')
root.title('Server Window')
root.wm_resizable(width=False, height=False)
# Create display area for selected items
display = tk.Text(root, height=10, width=30, bg='Orange', bd=4)
display.grid(row=1, column=3)
price_display = tk.Text(root, height=3, width=15, bg='Orange', bd=4)
price_display.grid(row=3, column=3)
#====================== Functions =================================
def fireFood():
# Every time a new item is selected i want a new total to be calculated and displayed
global menu
global price_display
global display
global select_option
total = 0
prices = []
# this inserts food item onto display
display.insert(tk.END,options.get())
prices.append([options.get(), menu[options.get()]])
for x in prices:
total = total + float(x[1])
# this shows price on lower display
price_display.insert(tk.END, total)
total += float(menu[options.get()])
def addList(arr):
cost = 0
arr.remove('\n')
total = [sum(float(x) for x in arr)]
for x in total:
cost += x
return cost
#======================================================================
# Create a Dictionary of items to be displayed in Combobox
menu = {'fries ':5, 'Burger ':10, 'Pizza ':15, 'Chicken ':8, 'Fish ':7.50}
menu_list = [x for x in menu.keys()]
menu_prices = [y for y in menu.values()]
options = ttk.Combobox(values=menu_list)
# Set default value for the combobox to 'Menu' to function as a pseudo label
options.set('Menu')
options.grid(row=0, column=0)
# Create a button that when pressed will get the value of combobox
select_option = ttk.Button(root, text='Select', command=fireFood)
select_option.grid(row=0, column=1)
root.mainloop()
This works for me.
price_display = tk.Text(root, height=3, width=15, bg='Orange', bd=4)
price_display.grid(row=3, column=3)
total = 0
#====================== Functions =================================
def fireFood():
# Every time a new item is selected i want a new total to be calculated and displayed
global menu
global price_display
global display
global select_option
global prices
global total # make total global
prices = []
# this inserts food item onto display
display.insert(tk.END,options.get())
# this shows price on lower display
total += float(menu[options.get()])
price_display.delete('1.0', 'end') # delete previous text
price_display.insert(tk.END, total)

Working with a GUI without using OOP

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()

Categories

Resources