How to change value of a variable when button is pressed tkinter - python

Im trying to detect a button press in tkinker but every method on google does not work for me, i want to change variable value for my python project.
Here's the basic code:
from tkinter import *
win= Tk()
win.geometry("500x600")
up = Button(win, text="⬆", bg="yellow", borderless=1, width=150, height=100, command = var = 1)
up.place(x=0, y = 500)
win.mainloop()
How do i do that?

Sourced from: To Detect Button Press In Python Tkinter Module
You could just place the variable change within a function
up = Button(win, text="⬆", bg="yellow", borderless=1, width=150, height=100, command=changeVar())
def changeVar():
var = 1
Or something close to this, assuming it's in the global namespace, since you're attemping to change it via var = 1 anyway.

Related

how could i update integer variable with tkinter?

i found a tutorial on google which integer value could be update by using .config(). So I had using the below code to update the value. I think my logic it wrong by put the while loop like that , but i not sure how could i update the a = a + 1 on to the gui.
My code :
import tkinter as tk
from random import randint
master_window = tk.Tk()
master_window.geometry("250x150")
master_window.title("IntVar Example")
lab = tk.Label(master_window)
integer_variable = tk.IntVar()
integer_variable.set(2)
label = tk.Label(master_window,text="output", height=50)
label.place(x=80, y=80)
a = 25
def update():
my_data=integer_variable.get(a) # read the value of selected radio button
label.config(text=str(my_data)) # Update the Label with data
while True:
a = a + 1
master_window.update()
master_window.mainloop()
The setup you have so far is quite strange and your intuition that the logic is wrong is accurate.
Here's an alternative to get you started - note how I refrain from using external variables and instead use the .set() and get() operations to change the value of the integer_variable:
import tkinter as tk
master_window = tk.Tk()
master_window.geometry("250x150")
master_window.title("IntVar Example")
integer_variable = tk.IntVar()
integer_variable.set(2)
label = tk.Label(master_window, text=integer_variable.get())
label.grid(row=0, column=0)
button = tk.Button(master_window, text="Update value", command=update)
button.grid(row=1, column=0)
def update():
curr_integer_variable_value = integer_variable.get()
updated_integer_value = curr_integer_variable_value + 1
integer_variable.set(updated_integer_value)
label.config(text=str(integer_variable.get()))
master_window.mainloop()

How can i update a variable after pressing buttons on tkinter?

There's an example of my code below.
I am trying to make a GUI with tkinter, in python. I want an app that has a variable, let's say var_list, that is introduced into a function as a parameter.I run this function using a button with command=lambda: analize(var_list)
I want to be able to modify the variable by pressing buttons (buttons to add strings to the list). And I have a function for that aswell:
def button_clicked(e):
if ((e["text"]).lower()) in var_list:
var_list.pop(var_list.index((e["text"]).lower())) #this adds a string to the list
else:
var_list.append((e["text"]).lower()) #this deletes the string from the list if it was already there
The function works, I tried printing the var_list and it gets updated everytime I press a button.
The problem is that I have to create the var_list as an empty list before, and when I run the function analize(var_list), it uses the empty list instead of the updated one.
Any idea on how to update the global var everytime I add/delete something from the list?
from tkinter import *
from PIL import ImageTk
def show_frame(frame):
frame.tkraise()
def button_clicked(e):
if ((e["text"]).lower()) in var_list:
var_list.pop(var_list.index((e["text"]).lower()))
else:
var_list.append((e["text"]).lower())
def analize(x):
#does stuff with the list
window = Tk()
frame1 = Frame(window)
frame2 = Frame(window)
canvas1 = Canvas(frame1,width = 1280, height = 720)
canvas1.pack(expand=YES, fill=BOTH)
image = ImageTk.PhotoImage(file="background.png")
var_list = []
button1 = Button(canvas1, text="Analize",font=("Arial"),justify=CENTER, width=10, command=lambda: [show_frame(frame2),analize(x=var_list)])
button1.place(x=(1280/2)-42, y=400)
button2 = Button(canvas1, text="String1",font=("Arial"),justify=CENTER, width=10, command=lambda: button_clicked(button2))
button2.place(x=(1280/2)-42, y=450)
button3 = Button(canvas1, text="String2",font=("Arial"),justify=CENTER, width=10, command=lambda: button_clicked(button3))
button3.place(x=(1280/2)-42, y=500)
Thank you
you can make a global variable eg:-global var
Now you can access it within other defination to manipulate the variable like this
global var
var = 0 # if you want to set a default value to the variable before calling the
function
def change_var():
global var
var = 1
USE OF GLOBAL
using global is highly recommended and is quite necessary if you are working with functions that contain or has the need to manipulate the variable
If global is not given inside the function, the variable will live inside the function and it cannot be accessed outside the function.
Hope this answer was helpful, btw, I am not sure if this the answer you are looking for as your question is not clear, maybe give a situation where you might think it might be necessary to change or update the variable
Sorry, I did not understand you but I guess this example will help you -
import tkinter as tk
root = tk.Tk()
var_list = []
def change_val(n):
var_list.append(n)
label1.config(text=var_list)
def remove():
try:
var_list.pop()
label1.config(text=var_list)
except:
pass
label1 = tk.Label(root,text=var_list)
label1.pack()
button1 = tk.Button(root,text='1',command=lambda:change_val(1))
button1.pack()
button2 = tk.Button(root,text='2',command=lambda:change_val(2))
button2.pack()
button3 = tk.Button(root,text='3',command=lambda:change_val(3))
button3.pack()
button4 = tk.Button(root,text='Pop Element',command=remove)
button4.pack()
root.mainloop()

tkinter, save the input as variable

I want to use the input value as variable and this is my code.
from tkinter import *
from tkinter import messagebox
window = Tk()
Label(window, text='Cavity number').grid(row=0)
CavNum = StringVar()
for i in range(1,8) :
globals()['L{}_CavNum'.format(i)] = StringVar()
globals()['L{}_CavNum'.format(i)] = Entry(window, textvariable=globals()['L{}_CavNum'.format(i)])
globals()['L{}_CavNum'.format(i)].grid(row=0, column=i)
window.geometry("1200x150")
window.mainloop()
everytime I do print(L1_CavNum), it says "<tkinter.Entry object .!entry>". please tell me what is the problem
You are re-using the same name for the entry widget as you use for StringVar. You could simply change globals()['L{}_CavNum'.format(i)] = StringVar() to globals()['L{}_CavNumSV'.format(i)] = StringVar() and print(L1_CavNum) to print(L1_CavNumSV.get()). However the .get() function will execute when your code runs so you will have to have a button or another event to callback the function.
I would do it like this.
from tkinter import *
def print_vars():
for x in range(len(cavity_string_vars)):
print(cavity_string_vars[x].get())
window = Tk()
Label(window, text='Cavity number').grid(row=0)
cavity_string_vars = []
cavity_entries = []
for i in range(7):
cavity_string_vars.append(StringVar())
cavity_entries.append(Entry(window, textvariable=cavity_string_vars[i]))
cavity_entries[i].grid(row=0, column=i)
print_button = Button(window, text="Print", command=print_vars)
print_button.grid(row=1, column=0)
window.geometry("1200x150")
window.mainloop()
To me associated arrays are much easier than naming each variable even when you program it as you have. Perhaps that is needed for your case.

Change the colour of a tkinter button generated in a loop

In python tkinter, I've got a program that generates multiple buttons with a default fg of red
from tkinter import *
root = Tk()
def dothis(i):
print(i)
button.config(fg='green')
for i in range(5):
button = Button(root, width=30, text="button{}".format(i), command=lambda i=i: dothis(i))
button.config(fg='red')
button.pack()
This creates this window:
In this program, I have attempted to make it so that once the button is pressed, the colour of the text (fg) turns green. Instead, when dothis(i) is called, it changes the colour of the last button generated to green. This is not what I want.
To summarise, when I click button3, I want to see this:
But instead, I see this (the last generated button is modified, not the one I want):
How can I work around this, while still keeping the buttons generated in a loop?
Note: The buttons must also be modifiable after changing the colour e.g. Once changed to green, it can be turned back to red.
You got the correct lambda expression, but the parameter you passed isn't related to the buttons you created. You should pass the Button widget as a parameter instead:
from tkinter import *
root = Tk()
def dothis(button):
button.config(fg='green')
for i in range(5):
button = Button(root, width=30, text="button{}".format(i))
button.config(fg='red', command=lambda i=button: dothis(i))
button.pack()
root.mainloop()
To achieve toggling between red and green, you can use ternary operator:
def dothis(button):
button.config(fg='green' if button["foreground"]=="red" else "red")
If you insist on all buttons except the last one being anonymous, and using command instead of binding events, you can use partials:
from tkinter import *
from functools import partial
root = Tk()
button_callbacks = {}
def on_click(button):
button.config(fg="green")
for i in range(5):
button = Button(root, width=30, text=f"button{i}", fg="red")
callback_name = f"on_click_{i}"
button_callbacks.update({callback_name: partial(on_click, button=button)})
button.config(command=button_callbacks[callback_name])
button.pack()
Using event binding would be a bit more straight-forward, but the behavior is not exactly the same as triggering a callback using command. Here's what that might look like:
from tkinter import *
root = Tk()
def on_click(event):
button = event.widget
button.config(fg="green")
for i in range(5):
button = Button(root, width=30, text=f"button{i}", fg="red")
button.bind("<Button-1>", on_click)
button.pack()

Display real-time variables values in a Gui in Python with Tkinter

I want to make a windows that will shoes the values of a variable in real-time in python with tkinter. The variable in question will be in a while loop. This is for a small physics project. Thanks for your help.
OK you haven't been very clear on exactly what your doing, but if you are going to update in a while loop you would do something such as getting whatever variable and then setting a variable on a label presumably.
import tkinter, time
from tkinter import *
#declare vars for readability
var1 = StringVar()
velocityOfBall = 0
gravity = 9.8
root = Tk()
def startDemo():
while True:
velocityOfBall += gravity
var1.set("Velocity: " + velocityOfBall)
time.sleep(1)
button1 = Button(root, command=startDemo).grid(row=0, column=0)
label1 = Label(root, textvariable = var1).grid(row=1, column=0)
root.mainloop()

Categories