how to make this python code run on raspberry pi - python

i wrote this code and it runs perfectly on my windows pc using PyCharm.
when i run it from my raspberry pi 2 using the default interpreter it acts weird- buttons don't always respond, and alarmList array won't print properly on command.
has anyone had this problem before?
code:
import time
from Tkinter import *
import tkMessageBox
date = [time.strftime('%Y', time.localtime(time.time())), time.strftime('%m', time.localtime(time.time())), time.strftime('%d', time.localtime(time.time())), time.strftime('%H', time.localtime(time.time())), time.strftime('%M', time.localtime(time.time())), time.strftime('%S', time.localtime(time.time()))]
main = Tk()
main.overrideredirect(True)
main.grid_columnconfigure(0, weight=3)
main.grid_rowconfigure(0, weight=3)
main.geometry("{0}x{1}+0+0".format(main.winfo_screenwidth(), main.winfo_screenheight()))
AlarmList = []
def setAlarm():
def submit_alarm():
get_alarm = [int(alarm_hour_entry.get()), int(alarm_minute_entry.get())]
alarm_hour_entry.delete(0, END)
alarm_minute_entry.delete(0, END)
if get_alarm[0] > 0 and get_alarm[0] < 23 and get_alarm[1] >= 0 and get_alarm[1] < 59:
AlarmList.append(get_alarm)
AlarmList.sort()
else:
tkMessageBox.showinfo("Invalid Time", "please enter a valid time, you fucking douchebag")
print AlarmList
alarm_set = Tk()
# alarm_set.configure(bg='white')
alarm_set.overrideredirect(True)
alarm_set.geometry("{0}x{1}+0+0".format(alarm_set.winfo_screenwidth(), alarm_set.winfo_screenheight()))
alarm_hour_label = Label(alarm_set, text="Alarm Hour:")
alarm_hour_entry = Entry(alarm_set)
alarm_hour_label.grid(row=0, column=0)
alarm_hour_entry.grid(row=0, column=1)
alarm_minute_label = Label(alarm_set, text="Alarm Minute:")
alarm_minute_entry = Entry(alarm_set)
alarm_minute_label.grid(row=1, column=0)
alarm_minute_entry.grid(row=1, column=1)
submit_button = Button(alarm_set, text='submit', command=submit_alarm)
submit_button.grid(row=2, column=1)
quit_alarm = Button(alarm_set, text="back to menu", command=alarm_set.destroy)
quit_alarm.grid(row=2, column=0)
alarm_set.mainloop()
def tick():
global time1
# get the current local time from the PC
time2 = time.strftime('%H:%M:%S')
# if time string has changed, update it
if time2 != time1:
time1 = time2
clock.config(text=time2)
# calls itself every 200 milliseconds
# to update the time display as needed
# could use >200 ms, but display gets jerky
clock.after(200, tick)
button1=Button(text='Set Alarm', font=('times', 15, 'bold'), command=setAlarm, bd=0, padx=2, pady=2)
button1.config(height=10, width=50)
button1.grid(row=0, column=0, sticky=W)
quit_main=Button(main, text='quit', font=('times', 15, 'bold'), command=main.destroy, bd=0, padx=30, pady=2)
#quit_main.configure(height=10, width=20)
quit_main.grid(row=3, column=0, sticky=W)
time1 = ''
clock = Label(main, font=('times', 100, 'bold'), bg='blue', fg='white')
clock.grid(row=1, columnspan=2, sticky=N)
settings_photo=PhotoImage(file="settings.gif")
settings=Button(image=settings_photo,bd=0)
settings.grid(row=3, column=1)
tick()
main.mainloop()

Related

How to compile python EXE script that can be used on windows computer without python programme

I am struggling ensure python script work on windows computer that does not have python installer. The script below only works on the computer with python software not sure where l am going wrong. Result is if uploaded on another computer no pictures or path is wrong. l am new to python can you please help as l dont know where l am going wrong. Thanks in advance
"""
from tkinter import*
import tkinter as tk
from tkinter import ttk
from datetime import datetime
windo = Tk()
windo.resizable(width=FALSE, height=FALSE)
windo.geometry("600x400")
windo.iconbitmap(r"C:\Users\breada\OneDrive\Desktop\Notes\image\Healthcare.ico")
house = "Mhungu"
def han():
print("Forms to be completed")
import tkinter as tk
from tkinter import ttk
from datetime import datetime
root = Tk()
root.resizable(width=FALSE, height=FALSE)
root.geometry("680x670")
root.iconbitmap(r"C:\Users\breada\OneDrive\Desktop\Notes\image\Healthcare.ico")
house = "Mhungu"
fun8 = Label(root, text="Running times comp :")
fun8.place(x=10,y=120)
var32 = IntVar()
chekbtn_1 = Checkbutton(root ,text="Yes", variable=var32)
chekbtn_1.place(x=180,y=120)
var33 = IntVar()
chekbtn_2 = Checkbutton(root ,text="No", variable=var33)
chekbtn_2.place(x=230,y=120)
def cli(value):
print("Severity of aggression")
print(value)
def clic(value):
print("Area of aggression")
print(value)
def click(value):
print("Nature of aggression")
print(value)
def save_funct():
print("Saved")
frame = LabelFrame(root, padx=5, pady=5)
v = tk.StringVar()
v.set("None")
lab2 = Label(frame, text="Select Level of Aggression", fg="blue", font=("Arial", 10))
lab2.pack()
radioButton1 = Radiobutton(frame, variable=v,value="1-No Concern", text="1-No Concern", command=lambda:cli(v.get()))
radioButton2 = Radiobutton(frame, variable=v, value="2-Not Severe",text="2-Not Severe",command=lambda:cli(v.get()) )
radioButton3 = Radiobutton(frame, variable=v, value="3-Slightly Severe",text="3-Slightly Severe",command=lambda:cli(v.get()) )
radioButton4 = Radiobutton(frame, variable=v, value="6-Extremely Severe",text="6-Extremely Severe",command=lambda:cli(v.get()) )
radioButton5 = Radiobutton(frame, variable=v,value="5-Severe", text="5-Severe", command=lambda:cli(v.get()))
radioButton6 = Radiobutton(frame, variable=v,value="4-Fairly Severe", text="6-Fairly Severe", command=lambda:cli(v.get()))
radioButton1.pack(side=LEFT)
radioButton2.pack(side=LEFT)
radioButton3.pack(side=LEFT)
radioButton4.pack(side=RIGHT)
radioButton5.pack(side=RIGHT)
radioButton6.pack(side=RIGHT)
frame.place(x=35, y=155)
frame1 = LabelFrame(root, padx=5, pady=5)
vv = tk.StringVar()
vv.set("None")
lab2 = Label(frame1, text="Areas of Aggressions", fg="blue", font=("Arial", 10))
lab2.pack()
radioButton1 = Radiobutton(frame1, variable=vv,value="Lounge", text="Lounge", command=lambda:clic(vv.get()))
radioButton2 = Radiobutton(frame1, variable=vv, value="Kitchen",text="Kitchen",command=lambda:clic(vv.get()) )
radioButton3 = Radiobutton(frame1, variable=vv, value="Bedroom 1",text="Bedroom 1",command=lambda:clic(vv.get()) )
radioButton4 = Radiobutton(frame1, variable=vv, value="Bedroom 2",text="Bedroom 2",command=lambda:clic(vv.get()) )
radioButton5 = Radiobutton(frame1, variable=vv,value="Bedroom 3", text="Bedroom 3", command=lambda:clic(vv.get()))
radioButton6 = Radiobutton(frame1, variable=vv,value="Dinning ", text="Dinning", command=lambda:clic(vv.get()))
radioButton1.pack(side=LEFT)
radioButton2.pack(side=LEFT)
radioButton3.pack(side=LEFT)
radioButton4.pack(side=RIGHT)
radioButton5.pack(side=RIGHT)
radioButton6.pack(side=RIGHT)
frame1.place(x=35, y=255)
frame2 = LabelFrame(root, padx=5, pady=5)
vvv = tk.StringVar()
vvv.set("None")
lab2 = Label(frame2, text="Nature of Aggression", fg="blue", font=("Arial", 10))
lab2.pack()
radioButton1 = Radiobutton(frame2, variable=vvv,value="Punching", text="Punching", command=lambda:click(vvv.get()))
radioButton2 = Radiobutton(frame2, variable=vvv, value="Kicking",text="Kicking",command=lambda:click(vvv.get()) )
radioButton3 = Radiobutton(frame2, variable=vvv, value="Pushing ",text="Pushing",command=lambda:click(vvv.get()) )
radioButton4 = Radiobutton(frame2, variable=vvv, value="Forceful",text="Forceful",command=lambda:click(vvv.get()) )
radioButton5 = Radiobutton(frame2, variable=vvv,value="Punching Walls", text="Punching Walls", command=lambda:click(vvv.get()))
radioButton6 = Radiobutton(frame2, variable=vvv,value="Clinch fists ", text="Clinch fists", command=lambda:click(vvv.get()))
radioButton1.pack(side=LEFT)
radioButton2.pack(side=LEFT)
radioButton3.pack(side=LEFT)
radioButton4.pack(side=RIGHT)
radioButton5.pack(side=RIGHT)
radioButton6.pack(side=RIGHT)
frame2.place(x=35, y=355)
buttnn = Button(root, text="Save", width=10, height=2, fg= "blue",command=save_funct)
buttnn.place(x=570, y=615)
root.mainloop()
def st_ii():
print("Redirected")
canvas=Canvas(width=400,height=200, bg="blue")
canvas.place(x=200,y=130)
photo=PhotoImage(file="C:\\Users\\breada\\OneDrive\\Desktop\\Forest.png")
canvas.create_image(0,0,image=photo, anchor=NW)
toolbar = Frame(windo, bg="powder blue", padx=3, pady=20)
insertButt= Button(toolbar,text = "A-Form",command =han)
insertButt.pack(side=LEFT, padx=6,pady=2)
shift_planButt = Button(toolbar, text= "B-Form",command =st_ii)
shift_planButt.pack(side=LEFT, padx=6,pady=2)
toolbar.pack(side=TOP,fill=X)
windo.mainloop()
"""
If you compile your script into an executable file, for example by using "auto-py-to-exe", then the resulting .exe-file can be run on any computer with the same architecture as the one you created the .exe file on.
You can include other files or folders containing pictures or icons using a simple GUI.
you can install it with pip:
$ pip install auto-py-to-exe
or directly from github:
https://github.com/brentvollebregt/auto-py-to-exe

Automatic calculation from treeview values - tkinter python

Please help. I am working on a table where the user enters the beginning of working hours Od and end of working hours Do.
The number of hours spent at work should then be calculated automatically. But now it doesn't count for me and I don't know where my mistake is anymore.
import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkcalendar import DateEntry
from tkinter.filedialog import asksaveasfile
from tkinter.messagebox import showinfo,askquestion
from tkinter import filedialog
import sys
import csv
# základ okna ###############################################
okno = tk.Tk()
okno.title("Evidence pracovní doby")
# menubar ###############################################
def openfile():
"""Položka "Otevřít" v menu "Soubor" """
with open("new.csv") as myfile:
csvread = csv.reader(myfile, delimiter=",")
for row in csvread:
tabulka.insert("", "end", values=row)
def savefile():
""" Položka "Uložit" v menu "Soubor" """
with open("new.csv", "w", newline="") as myfile:
csvwriter = csv.writer(myfile, delimiter=",")
for row_id in tabulka.get_children():
row = tabulka.item(row_id)["values"]
csvwriter.writerow(row)
showinfo("Uložení", "Uložení proběhlo v pořádku.")
def info_menu():
""" Položka "Info" v menu"""
info_okno = tk.Toplevel()
info_okno.title("Info")
Label(info_okno, text="WORK TIME v0.1", font="bold").grid(row=1, column=0, sticky="we", pady=5, padx=5)
Label(info_okno, text="Jakub Kolář\nkolarkuba#gmail.com\n2022").grid(row=2, column=0, sticky="we", pady=5, padx=5)
close_button = Button(info_okno,text = "Zavřít",command=lambda:info_okno.destroy()).grid(row=3, column=0, pady=5)
mb = Menu(okno)
file_menu = Menu(mb, tearoff=0)
file_menu.add_command(label="Otevřít poslední", command=openfile)
file_menu.add_command(label="Uložit", command=savefile)
file_menu.add_separator()
file_menu.add_command(label="Zavřít", command=lambda:okno.destroy())
mb.add_cascade(label="Soubor", menu=file_menu)
mb.add_command(label="Info", command=info_menu)
okno.config(menu=mb)
# Jméno ###############################################
Label(okno, text="Jméno").grid(row=2, column=0, sticky="w", padx=5)
jmeno = Entry(okno)
jmeno.insert(10,"")
jmeno.grid(row=3, column=0, sticky="w", padx=5)
# Součet ###############################################
Label(okno, text="Celkem hodin").grid(row=2, column=0, sticky="e", padx=5)
h = 0 # součet všech hodin
soucet = Entry(okno, width=5)
soucet.insert(10,h)
soucet.grid(row=3, column=0, sticky="e", padx=5, pady=5)
# tabulka ###############################################
tabulka = ttk.Treeview(okno)
tabulka.grid(row=4, column=0, sticky="w", padx=5)
# nastavení sloupců
tabulka["columns"] = ("Datum", "Od", "Do", "Hodin", "Misto", "Poznamka")
tabulka.column("#0", width=0, stretch=NO)
tabulka.column("Datum", anchor=CENTER, width=80)
tabulka.column("Od", anchor=CENTER, width=80)
tabulka.column("Do", anchor=CENTER, width=80)
tabulka.column("Hodin", anchor=CENTER, width=80)
tabulka.column("Misto", anchor=CENTER, width=150)
tabulka.column("Poznamka", anchor=CENTER, width=80)
# nastavení popisků sloupců
tabulka.heading("#0",text="",anchor=CENTER)
tabulka.heading("Datum",text="Datum",anchor=CENTER)
tabulka.heading("Od",text="Od",anchor=CENTER)
tabulka.heading("Do",text="Do",anchor=CENTER)
tabulka.heading("Hodin",text="Hodin",anchor=CENTER)
tabulka.heading("Misto",text="Místo",anchor=CENTER)
tabulka.heading("Poznamka",text="Poznámka",anchor=CENTER)
# data ###############################################
data = []
global count
count = 1
for zaznam in data:
tabulka.insert(parent='', index="end", iid=count, text="", values=(zaznam[0],
zaznam[1], zaznam[2], zaznam[3], zaznam[4], zaznam[5]))
count += 1
# Rámec vkládacích polí ###############################################
Input_frame = Frame(okno)
Input_frame.grid(row=5, column=0)
# Popisky vkládacích polí
Datum = Label(Input_frame,text="Datum")
Datum.grid(row=0,column=0)
Od = Label(Input_frame,text="Od")
Od.grid(row=0,column=1)
Do = Label(Input_frame,text="Do")
Do.grid(row=0,column=2)
Hodin = Label(Input_frame,text="")
Hodin.grid(row=0, column=3)
Misto = Label(Input_frame,text="Místo")
Misto.grid(row=0,column=4)
Poznamka = Label(Input_frame,text="Poznámka")
Poznamka.grid(row=0,column=5)
# vkládací pole
Datum_entry = DateEntry(Input_frame, width=8)
Datum_entry.grid(row=1,column=0)
Od_entry = Entry(Input_frame, width=8)
Od_entry.grid(row=1,column=1)
Do_entry = Entry(Input_frame, width=8)
Do_entry.grid(row=1,column=2)
Hodin_entry = Entry(width=0)
Misto_entry = Entry(Input_frame, width=24)
Misto_entry.grid(row=1,column=4)
Poznamka_entry = Entry(Input_frame, width=15)
Poznamka_entry.grid(row=1,column=5)
# Rámec tlačítek ###############################################
Button_frame = Frame(okno)
Button_frame.grid(row=6, column=0)
def input_record():
""" nastavení vyčítaní vkládacích polí"""
global count
global h
global citac_hodin
tabulka.insert(
parent="",
index="end",
iid = count,
text="",
values=(
Datum_entry.get(),
Od_entry.get(),
Od_entry.get(),
Hodin_entry.get(),
Misto_entry.get(),
Poznamka_entry.get()))
count += 1
Datum_entry.delete(0,END)
Od_entry.delete(0,END)
Do_entry.delete(0,END)
Misto_entry.delete(0,END)
Poznamka_entry.delete(0,END)
def delete():
""" Smazání vybraných dat z tabulky"""
selected_item = tabulka.selection()[0]
tabulka.delete(selected_item)
# button "Vložit záznam"
butt_plus = PhotoImage(file="/home/jakub/GitHub/Work_time/program/plus.png")
Input_button = Button(Button_frame, command=input_record, image=butt_plus,
relief="flat").grid(row=0, column=0, pady=5)
# button "Smazat záznam"
butt_minus = PhotoImage(file="/home/jakub/GitHub/Work_time/program/minus.png")
delete_button = Button(Button_frame, command=delete, image=butt_minus,
relief="flat").grid(row=0, column=1, pady=5)
# metoda hlavního okna mainloop, udržuje okno otevřené
okno.mainloop()
As it was mentioned in comments, there was no code for working_hours calculation in Your example.
Basically what You have to do is to track changes of Od and Do and calculate difference between them.
You can do that by passing textvariable into Entry and then trace any change of that variable.
For simplicity, I made an example only for full hours (no minutes) and valid hours are between 0-24. If those conditions are not met working_hours are set to 0. Of course You can then modify it to work with any other time format You need. I also trimmed Your example to necessary minimum.
Also, as this is Your first question. Stick with only english, especially for comments in Your code. You make it easier for others to help You.
import tkinter as tk
from tkinter import *
# základ okna ###############################################
okno = tk.Tk()
okno.title("Evidence pracovní doby")
# Rámec vkládacích polí ###############################################
Input_frame = Frame(okno)
Input_frame.grid(row=2, column=10)
# Popisky vkládacích polí
Od = Label(Input_frame, text="Od")
Od.grid(row=0, column=0)
Do = Label(Input_frame, text="Do")
Do.grid(row=0, column=1)
Hodin = Label(Input_frame, text="Hodin")
Hodin.grid(row=0, column=2)
# vkládací pole
Od_var = IntVar(value=9)
Od_entry = Entry(Input_frame, width=8, textvariable=Od_var)
Od_entry.grid(row=1, column=0)
Do_var = IntVar(value=17)
Do_entry = Entry(Input_frame, width=8, textvariable=Do_var)
Do_entry.grid(row=1, column=1)
Hodin_var = IntVar(value=8)
Hodin_entry = Entry(Input_frame, width=8, textvariable=Hodin_var, state="readonly")
Hodin_entry.grid(row=1, column=2)
def count_working_hours(*args):
global Od_var, Do_var, Hodin_var
try:
# Get Od and Do values (should be integer)
od = Od_var.get()
do = Do_var.get()
if not (0 <= od <= 24) or not (0 <= do <= 24) or od > do:
# invalid input: either od or do is not valid hours or od is higher than do
raise ArithmeticError
working_hours = do - od
except (TclError, ArithmeticError):
# In case of invalid input, set working hours to 0
working_hours = 0
finally:
# Set working hours
Hodin_var.set(working_hours)
# Trace Od and Do, call count_working_hours on change
Od_var.trace("w", count_working_hours)
Do_var.trace("w", count_working_hours)
# metoda hlavního okna mainloop, udržuje okno otevřené
okno.mainloop()

Increasing integers at specific time with elapsed time

I'm trying to make a program that will work as an "infomercial" in a separate window.
What i have are two integers (x and y) that both increase at the same time, in this case every 5 seconds. With the increasing values i need a timer displayed at the same time, that can show the elapsed time of how long the program has been running. I want to be albe to start and pause the program
So far i have an infinite while loop running where the values are increased every 5 seconds with time.sleep(5). I have tried implementing a timer in the form of a time.time(), and get it to work with the increments. I have also added buttons but don't work. I'm using tkinter as gui obtion.
How am i supposed to make it work? with threading?
import time
from tkinter import *
import math
usage = 0
yearly = 0
cubik = 0
price = 0
root = Tk()
root.title("Usage of fluid")
root.geometry("300x400")
var = IntVar()
var1 = IntVar()
var2 = StringVar()
var3 = StringVar()
var4 = StringVar()
def update_timeText():
current= time.strftime("%H:%M:%S")
timeText.configure(text=current)
root.after(1000, update_timeText)
def start():
global state
state = True
def pause():
global state
state = False
def exist():
root.destroy()
frame = LabelFrame(root, text="Liter", font=30)
frame.pack(fill = "both", expand="yes")
l = Label(frame, textvariable=var, font=20)
l.pack(pady = 3)
frame2 = LabelFrame(root, text="price from use", font=30)
frame2.pack(fill = "both", expand= "yes")
l2 = Label(frame2, textvariable=var1, font=16)
l2.pack(side = LEFT)
l3 = Label(frame2, text="dollars", font=16)
l3.pack(side=LEFT)
frame3 = LabelFrame(root, text="yearly", font=30)
frame3.pack(fill = "both", expand="yes")
m3 = Label(frame3, textvariable=var2, font=16, wraplength=0)
m3.pack(side=TOP)
l4 = Label(frame3, text="Liter", font=16)
l4.pack(side=TOP)
l5 = Label(frame3, text="m3", font=16)
l5.pack(side=BOTTOM, fill="both")
m4 = Label(frame3, textvariable=var3, font=16, wraplength=0)
m4.pack(side=BOTTOM)
frame4 = LabelFrame(root, text='runtime', font=30)
frame4.pack(fill = "both", expand="yes")
timeText= Label(frame4, text="", font=16)
timeText.pack()
startButton = Button(frame4, text='Start', command=start)
startButton.pack()
pauseButton = Button(frame4, text='Pause', command=pause)
pauseButton.pack()
quitButton = Button(frame4, text='Quit', command=quit)
quitButton.pack()
while True:
var.set(usage)
usage += 300
var1.set(round(price,1))
price+= 10
var2.set(yearly)
var3.set(round(cubik,1))
yearly += 300
cubik += 0.1
time.sleep(5)
update_timeText()
root.update_idletasks()
##update_timeText()
##root.mainloop()

How do I create an automatically updating GUI using Tkinter?

from Tkinter import *
import time
#Tkinter stuff
class App(object):
def __init__(self):
self.root = Tk()
self.labeltitle = Label(root, text="", fg="black", font="Helvetica 40 underline bold")
self.labeltitle.pack()
self.labelstep = Label(root, text="", fg="black", font="Helvetica 30 bold")
self.labelstep.pack()
self.labeldesc = Label(root, text="", fg="black", font="Helvetica 30 bold")
self.labeldesc.pack()
self.labeltime = Label(root, text="", fg="black", font="Helvetica 70")
self.labeltime.pack()
self.labelweight = Label(root, text="", fg="black", font="Helvetica 25")
self.labelweight.pack()
self.labelspeed = Label(root, text="", fg="black", font="Helvetica 20")
self.labelspeed.pack()
self.labeltemp = Label(root, text="", fg="black", font="Helvetica 20")
self.labeltemp.pack()
self.button = Button(root, text='Close recipe', width=25, command=root.destroy)
self.button.pack()
def Update(self, label, change):
label.config(text=str(change))
def main():
app = App()
app.mainloop()
if __name__ == "__main__":
main()
I'm trying to create a recipe display which will show the step, instructions, weight and other variables on a screen in a Tkinter GUI.
However, I do not know how to update the GUI to change with each new step of the recipe, as the content has to be dynamically updated based on user input (taken from a server). How can I achieve updating of the GUI's other elements based on the change in steps?
You can use after() to run function after (for example) 1000 miliseconds (1 second) to do something and update text on labels. This function can run itself after 1000 miliseconds again (and again).
It is example with current time
from Tkinter import *
import datetime
root = Tk()
lab = Label(root)
lab.pack()
def clock():
time = datetime.datetime.now().strftime("Time: %H:%M:%S")
lab.config(text=time)
#lab['text'] = time
root.after(1000, clock) # run itself again after 1000 ms
# run first time
clock()
root.mainloop()
BTW: you could use StringVar as sundar nataraj Сундар suggested
EDIT: (2022.01.01)
Updated to Python 3 with other changes suggested by PEP 8 -- Style Guide for Python Code
import tkinter as tk # PEP8: `import *` is not preferred
import datetime
# --- functions ---
# PEP8: all functions before main code
# PEP8: `lower_case_name` for funcitons
# PEP8: verb as function's name
def update_clock():
# get current time as text
current_time = datetime.datetime.now().strftime("Time: %H:%M:%S")
# udpate text in Label
lab.config(text=current_time)
#lab['text'] = current_time
# run itself again after 1000 ms
root.after(1000, update_clock)
# --- main ---
root = tk.Tk()
lab = tk.Label(root)
lab.pack()
# run first time at once
update_clock()
# run furst time after 1000ms (1s)
#root.after(1000, update_clock)
root.mainloop()
if you want to change label dynamically
self.dynamiclabel=StringVar()
self.labeltitle = Label(root, text=self.dynamiclabel, fg="black", font="Helvetica 40 underline bold")
self.dyanamiclabel.set("this label updates upon change")
self.labeltitle.pack()
when ever you get new value then just use .set()
self.dyanamiclabel.set("Hurrray! i got changed")
this apply to all the labels.To know more read this docs
If you are using labels, then you can use this:
label = tk.Label(self.frame, bg="green", text="something")
label.place(rely=0, relx=0.05, relwidth=0.9, relheight=0.15)
refresh = tk.Button(frame, bg="white", text="Refreshbutton",command=change_text)
refresh.pack(rely=0, relx=0.05, relwidth=0.9, relheight=0.15)
def change_text()
label["text"] = "something else"
Works fine for me, but it is dependent on the need of a button press.
I added a process bar in my window, and change its value according to randint for every 1 second using the update function:
from random import randint
def update():
mpb["value"] = randint(0, 100) # take process bar for example
window.after(1000, update)
update()
window.mainloop()
I wrote an example with Python 3.7
from tkinter import *
def firstFrame(window):
global first_frame
first_frame = Frame(window)
first_frame.place(in_=window, anchor="c", relx=.5, rely=.5)
Label(first_frame, text="ATTENTION !").grid(row=1,column=1,columnspan=3)
def secondFrame(window):
global second_frame
second_frame= Frame(window, highlightbackground=color_green, highlightcolor=color_green, highlightthickness=3)
second_frame.place(in_=window, anchor="c", relx=.5, rely=.5)
Label(second_frame, text="This is second frame.").grid(row=1, column=1, columnspan=3, padx=25, pady=(15, 0))
window = Tk()
window.title('Some Title')
window.attributes("-fullscreen", False)
window.resizable(width=True, height=True)
window.geometry('300x200')
firstFrame(window)
secondFrame(window)
first_frame.tkraise()
window.after(5000, lambda: first_frame.destroy()) # you can try different things here
window.mainloop()
Use root.config() and add a way to run

How to get tkinter Spinbox's value?

I am trying to make a timer on python Tkinter. To set the timer, I am using spinboxes. But, I am having trouble getting the value of my spinboxes to be turned into the variables time_h, time_m and time_s.
I have tried .get() but it is not working. When I tried printing the variables I got NameError: name 'spin_h' is not defined.
from tkinter import *
window = Tk()
window.title("Timer")
window.geometry('350x200')
hour = 0
minute = 0
second = 0
timer = (str(hour) + ':' + str(minute) + ':' + str(second))
lbl = Label(window, text=timer, font=("Arial Bold", 50))
hour_s = 0
min_s = 0
sec_s = 0
def save_time():
time_h = spin_h.get()
time_m = spin_m.get()
time_s = spin_s.get()
def new_window():
set_time = Tk()
spin_h = Spinbox(set_time, from_=0, to=10, width=5)
spin_h.grid(column=1,row=0)
spin_m = Spinbox(set_time, from_=0, to=60, width=5)
spin_m.grid(column=3,row=0)
spin_s = Spinbox(set_time, from_=0, to=60, width=5)
spin_s.grid(column=5,row=0)
h_label = Label(set_time, text='h', font=("Arial Bold", 10))
h_label.grid(column=2, row=0)
m_label = Label(set_time, text='m', font=("Arial Bold", 10))
m_label.grid(column=4, row=0)
s_label = Label(set_time, text='s', font=("Arial Bold", 10))
s_label.grid(column=6, row=0)
set_button = Button(set_time, text="Set Time", command=save_time)
set_button.grid(column=3, row=2)
btn = Button(window, text="Set Time", command=new_window)
btn.grid(column=3, row=2)
lbl.grid(column=3, row=0)
window.mainloop()
spin_h is a variable local to the new_window() function and there cannot be accessed by the save_time() function. You could declare it a global variable at the beginning of new_window() to fix that. - #Martineau (just made it into an answer instead of a comment).
Thanks Martineau

Categories

Resources