Python Forum
update text variable on label with keypress
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
update text variable on label with keypress
#1
I am trying to get a gui to update with four different possible letters to display in the left and right top corners of the window (a, b, c, d). I am having issues finding a good example of something similar already done.

This is really a main piece of my code I am trying to finish up on to wrap up and put together the separate code pieces to make everything work together.

I am using these event bindings:
        self.bind("<KeyPress-a>", self.on_keypress_a)
        self.bind("<KeyPress-b>", self.on_keypress_b)
        self.bind("<KeyPress-c>", self.on_keypress_c)
        self.bind("<KeyPress-d>", self.on_keypress_d)
    def on_keypress_a(self, evet):
        counter_value = self.counter.get()
        counter_value = counter_value-1 or INITIAL_COUNTER_VALUE
        self.counter.set(counter_value)

    def on_keypress_b(self, evet):
        counter_value = self.counter.get()
        counter_value = counter_value-1 or INITIAL_COUNTER_VALUE
        self.counter.set(counter_value)

    def on_keypress_c(self, evet):
        counter_value = self.counter.get()
        counter_value = counter_value-1 or INITIAL_COUNTER_VALUE
        self.counter.set(counter_value)

    def on_keypress_d(self, evet):
        print("d pressed")
The events work verifiably. I am just trying to wrap my brain around how to get the keypress to update a text string variable in a label in tkinter. I tried tk.Label, I could try ttk.Label.



import tkinter.ttk as ttk
import tkinter as tk
import datetime as dt
import time
#import os
#from tkinter import messagebox
from threading import Thread

 
# sets ammo count to initial value of 500 
INITIAL_COUNTER_VALUE = 500
# sets initial time at 100%
INITIAL_TIMER_VALUE = 33000 
# sets initial gun terminal ID
#sets gun rate
RMMAX = 0
# sets initial temparature
TEMP_INITIAL = 20
# sets text string for ammo/temp/low ammo status button
STATUS = "OK"

COOLED = 20

# initial class declaration for main body of program
class TkApp(tk.Tk):
# these arguments initialize the class and how to form arguments within 
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # set screen options
        self.geometry("640x400")
        self.configure(bg='black')
        self.title("Sentry Terminal")
        # locally initialize ammo count down
        self.counter = tk.IntVar()
        self.counter.set(INITIAL_COUNTER_VALUE)
        # locally sets the timer count down at 100%
        self.timer = tk.IntVar()
        self.timer.set(INITIAL_TIMER_VALUE)
        # locally sets rmbar to 0%
        self.rmcount = tk.IntVar()
        self.rmcount.set(RMMAX)
        # locally sets tempbar
        self.temperature = tk.IntVar()
        self.temperature.set(TEMP_INITIAL) 
        # locally sets text string for ammo status button
        self.stat = tk.StringVar()
        self.stat.set(STATUS)
#
        self.cooldown = tk.IntVar()
        self.stat.set(COOLED)

        # this arranges the grid row and column groupings.  
        tk.Grid.rowconfigure(self, 0, weight=1, uniform='c')
        tk.Grid.rowconfigure(self, 1, weight=1, uniform='b')
        tk.Grid.rowconfigure(self, 2, weight=1, uniform='b')
        tk.Grid.rowconfigure(self, 3, weight=1, uniform='b')
        tk.Grid.rowconfigure(self, 4, weight=1, uniform='b')
        tk.Grid.rowconfigure(self, 5, weight=1, uniform='b')
        tk.Grid.rowconfigure(self, 6, weight=1, uniform='b')
        tk.Grid.rowconfigure(self, 7, weight=1, uniform='b')
        tk.Grid.rowconfigure(self, 8, weight=1, uniform='b')

        tk.Grid.columnconfigure(self, 0, weight=1, uniform='a')
        tk.Grid.columnconfigure(self, 1, weight=1, uniform='a')
        tk.Grid.columnconfigure(self, 2, weight=1, uniform='a')
        tk.Grid.columnconfigure(self, 3, weight=1, uniform='a')
        tk.Grid.columnconfigure(self, 4, weight=1, uniform='a')
        tk.Grid.columnconfigure(self, 5, weight=1, uniform='a')

        # these are the button and label declarations
        rounds = tk.Label(self, justify=tk.CENTER, textvariable=self.counter)
        rounds.grid(row=3, column=2, columnspan=1, sticky="EW")
        label1 = tk.Label(self, textvariable=self.timer)
        label1.grid(row=7, column=2, sticky="EW")

        temp = tk.Button(self,justify=tk.CENTER,text="Temp",bg='black', fg='yellow', highlightbackground='yellow', highlightcolor='black',activebackground='yellow')
        temp.grid(row=2,column=4,sticky="NSEW")

        rm = tk.Button(self,justify=tk.CENTER,text="R(M)",bg='black', fg='yellow', highlightbackground='yellow', highlightcolor='black',activebackground='yellow')
        rm.grid(row=2,column=5,sticky="NSEW")
        # rounds rate bar
        rmbar = ttk.Progressbar(self, orient="vertical", variable=self.rmcount)
        rmbar.grid(row=3,column=5,rowspan=6, sticky="NS")

        # temperature bar
        tempbar = ttk.Progressbar(self, orient="vertical", variable=self.temperature)
        tempbar.grid(row=3,column=4,rowspan=6,sticky="NS")

        # declarative buttons
        timestat = tk.Button(self,bg='black',state=tk.DISABLED, fg='yellow',disabledforeground='yellow',highlightbackground='yellow',borderwidth=2,justify=tk.CENTER,text="TIME AT 100% \n (msecs)")
        timestat.grid(row=7,column=0,columnspan=2,sticky="NSEW")
        roundsr = tk.Button(self,bg='black',state=tk.DISABLED, fg='yellow',disabledforeground='yellow',highlightbackground='yellow',borderwidth=2,justify=tk.CENTER,text="Rounds \n Remaining")
        roundsr.grid(row=3,column=0,columnspan=2,sticky="NS")


        # crit menu bar
        crit = tk.Button(self,justify=tk.CENTER,textvariable=self.stat, bg='black', fg='yellow', highlightbackground='yellow', highlightcolor='black',activebackground='yellow')
        crit.grid(row=5,column=0,columnspan=2,sticky="NSEW")
        

        # static center header
        headernew = tk.Button(self, bg='black',state=tk.DISABLED,justify=tk.CENTER, text="UA 571-C \n REMOTE SENTRY WEAPON SYSTEM")
        headernew.grid(row=0,column=1,columnspan=4,rowspan=2,sticky="NSEW")




        # displays gun id on top left and right of screen
        gun_1 = tk.Label(self, borderwidth=7,bg='black',fg='yellow',disabledforeground='yellow',state=tk.DISABLED,text="kp")
        gun_1.grid(row=0,column=0,rowspan=2,sticky="NS")
        gun_2 = tk.Button(self, borderwidth=7,bg='black',fg='yellow',disabledforeground='yellow',state=tk.DISABLED,text="kp")
        gun_2.grid(row=0,column=5,rowspan=2,sticky="NS")


        # this quits by clicking a button labeled q
        quit = tk.Button(self, bg='black', fg='yellow', text='q', command=self.quit)
        quit.grid(row=8,column=0,sticky="SW")

        # these are the attachments for input from keyboard into the application
        # These are the button inputs from the original flash app that were used
        # I added a q as well to quit and close window in case there was a need to close

        self.bind("<KeyPress-f>", self.on_keypress_f)
        self.bind("<KeyRelease-f>", self.on_keyrelease_f)
        self.bind("<KeyPress-a>", self.on_keypress_a)
        self.bind("<KeyPress-b>", self.on_keypress_b)
        self.bind("<KeyPress-c>", self.on_keypress_c)
        self.bind("<KeyPress-d>", self.on_keypress_d)
        self.bind("<KeyPress-r>", self.on_keypress_r)
        self.bind("<KeyPress-q>", self.on_keypress_q)
        self.bind("<KeyPress-space>", self.on_keypress_space)
    #    self.coolbar(temperature_count)

    def coolbar(self):
        temperature_count = self.temperature.get()
#        self.temperature.set(temperature_count)
        while temperature_count >= 20:
#          self.temperature.set(temperature_count)
          temperature_count = temperature_count-1
          time.sleep(0.1)
          self.temperature.set(temperature_count)
          print("key not pressed", temperature_count)
 #         temperature_count = 
 #         time.sleep(0.1)  
 #       tempbar = ttk.Progressbar(self, orient="vertical", variable=self.temperature)
  #      tempbar.grid(row=3,column=4,rowspan=6,sticky="NS")        

    def overheat(self):
        temperature_count = self.temperature.get()
        temperature_count = temperature_count-1
        self.temperature.set(temperature_count)
        print("overheat", temperature_count)
        self.after(0.04, overheat)


    # this defines the fire ammo count down sequence and resets 
    def on_keypress_f(self, evet):
        
        counter_value = self.counter.get()
        counter_value = counter_value-1 or INITIAL_COUNTER_VALUE
        self.counter.set(counter_value)
        # this is logic to try and get ammo warnings
        if counter_value == 490:
          
          stat_value = "OUT"
        else:
          stat_value = "OK"
          self.stat.set(stat_value)
        # this sets the time at 100%
        timer_value = self.timer.get()
        timer_value = timer_value-66 or INITIAL_TIMER_VALUE
        self.timer.set(timer_value)
        # this sets the rmbar to 40%
        rmcount_count = self.rmcount.get()
        rmcount_count = 40
        self.rmcount.set(rmcount_count)
        # this sets the temperature
        temperature_count =  self.temperature.get()
        temperature_count = temperature_count+1
        self.temperature.set(temperature_count)
        if temperature_count == 90:
          self.coolbar()






    def on_keyrelease_f(self, evet):
        #this adds logic to say rate is zero if not firing
        rmcount_count = self.rmcount.get()
        rmcount_count = 0
        self.rmcount.set(rmcount_count)
        # this adds logic to say if not firing cool down
#        temperature_count =  self.temperature.get()
 #       temperature_count = temperature_count-10
  #      self.temperature.set(temperature_count)
        self.coolbar()
   


    # this sets the gun terminal identification
    # this can also be expanded to do other things if you want to alter the script
    def on_keypress_a(self, evet):
        counter_value = self.counter.get()
        counter_value = counter_value-1 or INITIAL_COUNTER_VALUE
        self.counter.set(counter_value)

    def on_keypress_b(self, evet):
        counter_value = self.counter.get()
        counter_value = counter_value-1 or INITIAL_COUNTER_VALUE
        self.counter.set(counter_value)

    def on_keypress_c(self, evet):
        counter_value = self.counter.get()
        counter_value = counter_value-1 or INITIAL_COUNTER_VALUE
        self.counter.set(counter_value)

    def on_keypress_d(self, evet):
        print("d pressed")

    def on_keypress_space(self, evet):
        print("space pressed")

# this reloads the window, you have to click it to make it the active window again
    def on_keypress_r(self, evet):
        self.destroy()
        self.__init__()

# this quits and closes the window by hitting a single key
    def on_keypress_q(self, evet):
        self.quit()
 
# this executes the main loop and tkinter self delcared class.  It declares the function then runs it in the main loop. 
tk_app = TkApp()

tk_app.mainloop()
I am aware there are some unused elements and duplicative things, but I am trying to get things working, then once it is working I clean up the code, add exhaustive documentation, and then wrap things up.
These are the headers I want to update:
        gun_1 = tk.Label(self, borderwidth=7,bg='black',fg='yellow',disabledforeground='yellow',state=tk.DISABLED,text="kp")
        gun_1.grid(row=0,column=0,rowspan=2,sticky="NS")
        gun_2 = tk.Button(self, borderwidth=7,bg='black',fg='yellow',disabledforeground='yellow',state=tk.DISABLED,text="kp")
        gun_2.grid(row=0,column=5,rowspan=2,sticky="NS")
Here is a link where you can download the flash software piece that I am trying to replicate into python:
http://forum.alienslegacy.com/viewtopic.php?f=3&t=3019

I am doing it in python as, as far as I know, python will be around for decades to come. It is the predominant server scripting os, it is getting increasingly popular on windows. mac already has rudimentary support for it built in due to the nextstep/os and bsd underpinnings. Android already somewhat natively supports python as does IOS to a much more limited extent. The kicker on android is that java is fixing to get retired and they are transitioning to using kotlin language, but the core os still runs heavily on java so I am not sure if they are going to switch to a c-like basis or python or something else. But as far as I can tell python support over time is going to continue to increase over time as many more entities adopt is due to its strong community support and insanely massive library base of modules.

I am just trying to future proof and idiot proof things as much as I can as I try to get this completed so if someone has to come back in 30 years and update functions, there are reference points and notes to follow on what does what. How many fortran and cobol programmers are there working now? a lot of programs at government and agency levels run on those two languages. Java and flash are going the same route and in my estimation are becoming the new fortran and cobol.
Reply
#2
(Apr-17-2021, 07:03 PM)knoxvilles_joker Wrote: I am trying to get a gui to update with four different possible letters to display in the left and right top corners of the window (a, b, c, d). I am having issues finding a good example of something similar already done.
This doesn't clearly describe what you intend to do, what decides which of the four choices (a, b, c, d) is made and what decides what goes to which corner?

(Apr-17-2021, 07:03 PM)knoxvilles_joker Wrote: I am just trying to wrap my brain around how to get the keypress to update a text string variable in a label in tkinter. I tried tk.Label, I could try ttk.Label.
you have a text string variable in the code already
self.stat = tk.StringVar()
that is updated on on_keypress_f
using
self.stat.set(stat_value)
which is updating a button
crit = tk.Button(self,justify=tk.CENTER,textvariable=self.stat, bg='black', fg='yellow', highlightbackground='yellow', highlightcolor='black',activebackground='yellow')
do the same thing for a label using the textvariable parameter
Reply
#3
(Apr-17-2021, 08:40 PM)Yoriz Wrote:
(Apr-17-2021, 07:03 PM)knoxvilles_joker Wrote: I am trying to get a gui to update with four different possible letters to display in the left and right top corners of the window (a, b, c, d). I am having issues finding a good example of something similar already done.
This doesn't clearly describe what you intend to do, what decides which of the four choices (a, b, c, d) is made and what decides what goes to which corner?

(Apr-17-2021, 07:03 PM)knoxvilles_joker Wrote: I am just trying to wrap my brain around how to get the keypress to update a text string variable in a label in tkinter. I tried tk.Label, I could try ttk.Label.
you have a text string variable in the code already
self.stat = tk.StringVar()
that is updated on on_keypress_f
using
self.stat.set(stat_value)
which is updating a button
crit = tk.Button(self,justify=tk.CENTER,textvariable=self.stat, bg='black', fg='yellow', highlightbackground='yellow', highlightcolor='black',activebackground='yellow')
do the same thing for a label using the textvariable parameter


Durr, I am a dunce. Were that code piece a snake I would be dead on arrival at the hospital.

Your points are valid. I was not explicitly clear:
If "A" is pressed, A displays in the left and right upper corners
If "B" is pressed, B displays in the left and right upper corners
If "C" is pressed, C displays in the left and right upper corners
If "D" is pressed, D displays in the left and right upper corners

That was so easy I overlooked the darned solution.
Declare the global text string:
GUN = ""
Declare a local variable text string:
        self.gun = tk.StringVar()
        self.gun.set(GUN)
Set these binds:
        self.bind("<KeyPress-a>", self.on_keypress_a)
        self.bind("<KeyPress-b>", self.on_keypress_b)
        self.bind("<KeyPress-c>", self.on_keypress_c)
        self.bind("<KeyPress-d>", self.on_keypress_d)
to these functions:
    def on_keypress_a(self, evet):
        which_gun = self.gun.get()
        which_gun = "A"
        self.gun.set(which_gun)

    def on_keypress_b(self, evet):
    def on_keypress_a(self, evet):
        which_gun = self.gun.get()
        which_gun = "B"
        self.gun.set(which_gun)

    def on_keypress_c(self, evet):
    def on_keypress_a(self, evet):
        which_gun = self.gun.get()
        which_gun = "C"
        self.gun.set(which_gun)

    def on_keypress_d(self, evet):
    def on_keypress_a(self, evet):
        which_gun = self.gun.get()
        which_gun = "D"
        self.gun.set(which_gun)
Which updates these labels:
        # displays gun id on top left and right of screen
        gun_1 = tk.Label(self, borderwidth=7,bg='black',fg='yellow',disabledforeground='yellow',state=tk.DISABLED,textvariable=self.gun)
        gun_1.grid(row=0,column=0,rowspan=2,sticky="NS")
        gun_2 = tk.Button(self, borderwidth=7,bg='black',fg='yellow',disabledforeground='yellow',state=tk.DISABLED,textvariable=self.gun)
        gun_2.grid(row=0,column=5,rowspan=2,sticky="NS")
Reply
#4
And in all honesty once I get the community TV 30 minute twice monthly show off the ground this forum and this solution is definitely getting shown.

And I have added a credits(kudos) splash screen where I will be adding all that helped here. I have no issues giving attribution where help was given.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] Make my button text update? Skata100 1 249 Aug-07-2021, 05:37 AM
Last Post: deanhystad
  [Tkinter] bind lambda keypress counter knoxvilles_joker 15 1,748 Apr-19-2021, 01:56 AM
Last Post: knoxvilles_joker
  Updating button text based upon different variable values knoxvilles_joker 0 547 Apr-18-2021, 04:13 AM
Last Post: knoxvilles_joker
  [Tkinter] tkinter.Menu – How to make text-variable? Sir 3 1,758 Mar-10-2021, 04:21 PM
Last Post: Sir
  How to read text in kivy textinput or Label jadel440 1 1,208 Dec-29-2020, 10:47 AM
Last Post: joe_momma
  [Kivy] Kivy text label won't shows up! AVD_01 1 1,329 Jun-21-2020, 04:01 PM
Last Post: AVD_01
  [Tkinter] Python 3 change label text gw1500se 6 1,907 May-08-2020, 05:47 PM
Last Post: deanhystad
  [Tkinter] how to update label text from list Roshan 8 1,968 Apr-25-2020, 08:04 AM
Last Post: Roshan
  [PyQt] Python PyQt5 - Change label text dynamically based on user Input ppel123 1 6,928 Mar-20-2020, 07:21 AM
Last Post: deanhystad
  Printing Variable into the label ardvci 5 1,324 Mar-19-2020, 09:35 PM
Last Post: joe_momma

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020