Tkinter: Changing value of a Textbox after calculation to avoid duplicates - python

from tkinter import *
class HHRG:
def __init__(self, root):
self.root = root
self.RnReg = 50
self.RnResump = 80
self.RnCert = 80
self.RnDC = 70
self.RnSOC = 90
self.LvnReg = 40
self.LvnOut = 35
self.Hha = 25
self.Pt = 75
self.Ot = 75
self.St = 75
self.HHRGValue = IntVar()
self.RnRegValue = IntVar()
self.RnResumpValue = IntVar()
self.RnCertValue = IntVar()
self.RnDCValue = IntVar()
self.RnSOCValue = IntVar()
self.LvnRegValue = IntVar()
self.LvnOutValue = IntVar()
self.HhaValue = IntVar()
self.PtValue = IntVar()
self.OtValue = IntVar()
self.StValue = IntVar()
###LABELS###
self.HHRGLabel = Label(self.root, text="HHRG")
self.RnRegLabel = Label(self.root, text="Regular Rn Visits")
self.RnResumpLabel = Label(self.root, text="Rn Resumption Visits")
self.RnCertLabel = Label(self.root, text="Rn recertification Visits")
self.RnDCLabel = Label(self.root, text="Rn D/C Visits")
self.RnSOCLabel = Label(self.root, text="Rn SOC Visits")
self.LvnRegLabel = Label(self.root, text="Regular Lvn Visits")
self.LvnOutLabel = Label(self.root, text="Lvn Outlier Visits")
self.HhaLabel = Label(self.root, text="HHA visits")
self.PtLabel = Label(self.root, text="Pt Visits")
self.OtLabel = Label(self.root, text="Ot Visits")
self.StLabel = Label(self.root, text="St Visits")
self.TotalLabel = Label(self.root, text="Net Total")
###ENTRY BOXES###
self.HHRGEntry = Entry(self.root, textvariable=self.HHRGValue)
self.RnRegEntry = Entry(self.root, textvariable=self.RnRegValue)
self.RnResumpEntry = Entry(self.root, textvariable=self.RnResumpValue)
self.RnCertEntry = Entry(self.root, textvariable=self.RnCertValue)
self.RnDCEntry = Entry(self.root, textvariable=self.RnDCValue)
self.RnSOCEntry = Entry(self.root, textvariable=self.RnSOCValue)
self.LvnRegEntry = Entry(self.root, textvariable=self.LvnRegValue)
self.LvnOutEntry = Entry(self.root, textvariable=self.LvnOutValue)
self.HhaEntry = Entry(self.root, textvariable=self.HhaValue)
self.PtEntry = Entry(self.root, textvariable=self.PtValue)
self.OtEntry = Entry(self.root, textvariable=self.OtValue)
self.StEntry = Entry(self.root, textvariable=self.StValue)
self.TotalEntry = Text(root, height=2, width=10)
self.clearButton = Button(root, text="Clear")
self.clearButton.bind("<Button-1>", self.clear)
self.calculatebutton = Button(root, text="Calculate", width=10)
self.calculatebutton.bind("<Button-1>", self.clear)
self.calculatebutton.bind("<Button-1>", self.calculate)
####LABEL GRIDS###
self.HHRGLabel.grid(row=0, column=0)
self.RnRegLabel.grid(row=1, column=0)
self.RnResumpLabel.grid(row=2, column=0)
self.RnCertLabel.grid(row=3, column=0)
self.RnDCLabel.grid(row=4, column=0)
self.RnSOCLabel.grid(row=5, column=0)
self.LvnRegLabel.grid(row=6, column=0)
self.LvnOutLabel.grid(row=7, column=0)
self.HhaLabel.grid(row=8, column=0)
self.PtLabel.grid(row=9, column=0)
self.OtLabel.grid(row=10, column=0)
self.StLabel.grid(row=11, column=0)
self.TotalLabel.grid(row=12, column=0)
###ENTRY GRIDS###
self.HHRGEntry.grid(row=0, column=1)
self.RnRegEntry.grid(row=1, column=1)
self.RnResumpEntry.grid(row=2, column=1)
self.RnCertEntry.grid(row=3, column=1)
self.RnDCEntry.grid(row=4, column=1)
self.RnSOCEntry.grid(row=5, column=1)
self.LvnRegEntry.grid(row=6, column=1)
self.LvnOutEntry.grid(row=7, column=1)
self.HhaEntry.grid(row=8, column=1)
self.PtEntry.grid(row=9, column=1)
self.OtEntry.grid(row=10, column=1)
self.StEntry.grid(row=11, column=1)
self.TotalEntry.grid(row=12, column=1)
self.calculatebutton.grid(columnspan=2, pady=10)
self.clearButton.grid(row=13, column=1)
def calculate(self, event):
values = [(self.RnRegValue.get() * self.RnReg),
(self.RnResumpValue.get() * self.RnResump),
(self.RnCertValue.get() * self.RnCert),
(self.RnDCValue.get() * self.RnDC),
(self.RnSOCValue.get() * self.RnSOC),
(self.LvnRegValue.get() * self.LvnReg),
(self.LvnOutValue.get() * self.LvnOut),
(self.HhaValue.get() * self.Hha),
(self.PtValue.get() * self.Pt),
(self.OtValue.get() * self.Ot),
(self.StValue.get() * self.St)]
self.total = 0
for i in values:
self.total += i
result = self.HHRGValue.get() - self.total
self.TotalEntry.insert(END, result)
def clear(self, event):
self.TotalEntry.delete("1.0", END)
root = Tk()
a = HHRG(root)
root.mainloop()
So i've got this modified calculator of mine and the problem with it is everytime you calculate. it returns outputs as desired but if you click it twice
it'll duplicate
I tried binding the self.calculatebutton to my clear() method but it wouldn't prevent the duplication of the results
my question is. How can we make it calculate the desired output but wipe the previous output at the same time to prevent duplicates? so if someone presses the calculate button multiple times it'll only output one total not multiple ones like the picture above

This code is where the problem lies:
self.calculatebutton = Button(root,text="Calculate",width=10)
self.calculatebutton.bind("<Button-1>",self.clear)
self.calculatebutton.bind("<Button-1>",self.calculate)
When you call bind, it will replace any previous binding of the same event to the same widget. So, the binding to self.clear goes away when you add the binding to self.calculate. While there are ways to bind multiple functions to an event, usually that is completely unnecessary and leads to difficult-to-maintain code.
The simple solution is for your calculate function to call the clear function before adding a new result:
def calculate(self,event):
...
result = self.HHRGValue.get() - self.total
self.clear(event=None)
self.TotalEntry.insert(END,result)
Note: if this is the only time you'll call clear, you can remove the event parameter from the function definition, and remove it from the call.
On a related note: generally speaking you should not use bind on buttons. The button has built-in bindings that normally work better than your custom binding (they handle keyboard traversal and button highlighting, for example).
The button widget has a command attribute which you normally use instead of a binding. In your case it would look like this:
self.calculatebutton = Button(..., command=self.calculate)
When you do that, your calculate method no longer needs the event parameter, so you'll need to remove it. If you want to use the calculate function both from a command and from a binding, you can make the event optional:
def calculate(self, event=None)

A simple fix could be to just call your clear method in your calculate method, before inserting the text into your TotalEntry text widget.
Try this:
def calculate(self,event):
values = [(self.RnRegValue.get() * self.RnReg),
(self.RnResumpValue.get() * self.RnResump),
(self.RnCertValue.get() * self.RnCert),
(self.RnDCValue.get() * self.RnDC),
(self.RnSOCValue.get() * self.RnSOC),
(self.LvnRegValue.get() * self.LvnReg),
(self.LvnOutValue.get() * self.LvnOut),
(self.HhaValue.get() * self.Hha),
(self.PtValue.get() * self.Pt),
(self.OtValue.get() * self.Ot),
(self.StValue.get() * self.St)]
self.total = 0
for i in values:
self.total += i
result = self.HHRGValue.get() - self.total
self.clear(event)
self.TotalEntry.insert(END,result)

Related

How to Add up multiple entry in Tkinter

I work on a program that calculates the macros of each meal. You can enter a value in gram and it calculates for each aliment your intake. I would like now to add these values together when I push multiple buttons. Then I'll display the value somewhere and maybe I could do a graph after.
Here I show what my program looks like :
import tkinter as tk
def value_kiwi():
value = ent_quantity.get()
formula = (float(value)/100)
cal = 53
pro = 1.6
glu = 11.1
li = 0.3
Calories = (cal) * formula
Protéines = (pro) * formula
Glucides = (glu) * formula
Lipides = (li) * formula
lbl_cal["text"] =f"{Calories}"
lbl_prot["text"] = f"{Protéines}"
lbl_glu["text"] = f"{Glucides}"
lbl_lip["text"] = f"{Lipides}"
def value_banane():
value = ent_quantity.get()
formula = (float(value)/100)
cal = 90
pro = 1.5
glu = 20.1
li = 0
Calories = (cal) * formula
Protéines = (pro) * formula
Glucides = (glu) * formula
Lipides = (li) * formula
lbl_cal["text"] =f"{Calories}"
lbl_prot["text"] = f"{Protéines}"
lbl_glu["text"] = f"{Glucides}"
lbl_lip["text"] = f"{Lipides}"
window = tk.Tk()
window.title("Calculateur de Calories et Nutriments")
frm_entry = tk.Frame(master=window)
ent_quantity = tk.Entry(master=frm_entry, width=5)
ent_quantity.grid(row=1, column=0,)
lbl_cal = tk.Label(master=window)
lbl_cal.grid(row=1, column=1,)
lbl_prot = tk.Label(master=window)
lbl_prot.grid(row=1, column=2)
lbl_glu = tk.Label(master=window)
lbl_glu.grid(row=1, column=3)
lbl_lip = tk.Label(master=window)
lbl_lip.grid(row=1, column=4)
btn_kiwi = tk.Button(
master=window,
text="Kiwi",
command=value_kiwi,
)
btn_banane = tk.Button(
master=window,
text="Banane",
command=value_banane,
)
lbl_calories = tk.Label(master=window, text="Calories",)
lbl_proteines = tk.Label(master=window, text="Protéines")
lbl_glucides = tk.Label(master=window, text="Glucides")
lbl_lipides = tk.Label(master=window, text="Lipides")
lbl_fruits = tk.Label(master=window, text="Fruits")
frm_entry.grid(row=1, column=0, padx=10)
lbl_calories.grid(row=0,column=1, padx=5, sticky="w")
lbl_proteines.grid(row=0, column=2, padx=10)
lbl_glucides.grid(row=0, column=3, padx=10)
lbl_lipides.grid(row=0,column =4, padx=10)
lbl_fruits.grid(row=1,column =5, padx=10)
btn_kiwi.grid(row=2, column=5, pady=10)
btn_banane.grid(row=3, column=5, pady=10)
window.mainloop()
Ok, I think I improved Your code:
from tkinter import Tk, Button, Entry, Label
class MainWindow(Tk):
def __init__(self):
Tk.__init__(self)
self.title('Nutrient calculator')
# entry
Label(self, text='Amount').grid(row=0, column=0)
self.amount = Entry(self, width=5, bg='light grey')
self.amount.grid(row=1, column=0)
# calories
Label(self, text='Calories').grid(row=0, column=1)
self.calories = Label(self)
self.calories.grid(row=1, column=1)
# proteins
Label(self, text='Proteins').grid(row=0, column=2)
self.proteins = Label(self)
self.proteins.grid(row=1, column=2)
# glucose
Label(self, text='Glucose').grid(row=0, column=3)
self.glucose = Label(self)
self.glucose.grid(row=1, column=3)
# lipids
Label(self, text='Lipids').grid(row=0, column=4)
self.lipids = Label(self)
self.lipids.grid(row=1, column=4)
# list of all labels
self.data_labels = [self.calories, self.proteins, self.glucose, self.lipids]
# error label for if no value is entered or it cannot be converted
self.error_label = Label(self, text='Use integer or float value!')
# stuff for adding multiple foods
self.do_add = False
self.nutrient_list = []
self.plus_btn = Button(self, text='Add', command=self.add)
self.plus_btn.grid(row=3, column=0, columnspan=4, sticky='nwes')
def display_values(self, value_list):
self.nutrient_list.append(value_list)
if len(self.nutrient_list) == 2 and not self.do_add:
self.nutrient_list.pop(0)
elif len(self.nutrient_list) > 2 and not self.do_add:
self.nutrient_list = [self.nutrient_list[-1]]
print(self.nutrient_list)
if self.do_add:
value_list = []
for i in range(len(self.nutrient_list[0])):
total_value = 0
for item in self.nutrient_list:
total_value += item[i]
value_list.append(total_value)
for text, label in zip(value_list, self.data_labels):
label.config(text=f'{text:.2f}')
self.do_add = False
def handle_value_error(self):
self.error_label.grid(row=2, column=0, columnspan=4)
def add(self):
self.do_add = True
self.amount.delete(0, 'end')
class Values:
def __init__(self, name, row, column, calories, proteins, glucose, lipids):
self.parent = root
self.name = name
self.row = row
self.column = column
self.calories = calories
self.proteins = proteins
self.glucose = glucose
self.lipids = lipids
self.stuff_list = [self.calories, self.proteins, self.glucose, self.lipids]
self.button = Button(self.parent, text=self.name, command=self.set_values)
self.button.grid(row=self.row, column=self.column, sticky='nwse')
def set_values(self):
value_list = []
value_ = self.parent.amount.get()
try:
formula = float(value_) / 100
self.parent.error_label.grid_forget()
for item in self.stuff_list:
item *= formula
value_list.append(item)
self.parent.display_values(value_list)
except ValueError:
self.parent.handle_value_error()
root = MainWindow()
kiwi = Values('Kiwi', 2, 4, calories=53, proteins=1.6, glucose=11.1, lipids=0.3)
banana = Values('Banana', 3, 4, calories=90, proteins=1.5, glucose=20.1, lipids=0)
root.mainloop()
it is not necessarily better however a few benefits from using this code are:
better organization (IMO) since it uses classes which make it pretty neat (however You have to have an understanding over them)
takes less space - what I mean is that now, to define a new food, You just have to initiate the Values class and give it the necessary arguments. You can take an example from the given instances.
possibly easier to expand (both because better organization and takes less space)
I edited the code so now it should have that functionality, the way it works is You choose an amount , then fruit and if You want to add more, press add button, then choose amount, press food and it will display the total so far, then again, if You want to add more press add and then put in an amount and press the fruit, currently the way to 'clear' is to press any food button and it should then reset the whole list and keep only the one that was just pressed and then repeat.

TKinter GUI freezing with root.after

I'm trying to create code to incrementally increase the voltage on a DC power supply over the span of an input duration. I've set up a GUI for doing this (it's my first try making a GUI, sorry if the code is weird), and everything works ... except that the GUI freezes while the code is executing so I can't stop the loop. I've looked into this for several hours and learned to use root.after instead of time.sleep, but it doesn't seem to have helped in the HeatLoop function. The GUI updates now, but only sporadically and there's still the "wait cursor" showing up when I mouse over the GUI. Is there some way to fix this?
I modified the code I'm using below so it should work on any computer without needing to be edited.
import datetime
import time
from tkinter import *
class GUIClass:
def __init__(self, root):
"""Initialize the GUI"""
self.root = root
self.percent = StringVar()
self.percent.set("00.00 %")
self.error = StringVar()
self.STOP = False
self.error.set("---")
self.currentvoltage = StringVar()
self.currentvoltage.set("Current Voltage: 00.00 V")
self.DT = datetime.datetime
# Create and attach labels
label1 = Label(root, text='Voltage')
label2 = Label(root, text='Ramp Duration')
label3 = Label(root, text='Percent Done: ')
label4 = Label(root, textvariable=self.percent)
label5 = Label(root, text="Error Message: ")
label6 = Label(root, textvariable=self.error)
label7 = Label(root, textvariable=self.currentvoltage)
label1.grid(row=0, column=0, sticky=W)
label2.grid(row=1, column=0, sticky=W)
label3.grid(row=2, column=0, sticky=W)
label4.grid(row=2, column=1, sticky=W)
label5.grid(row=3, column=0, sticky=W)
label6.grid(row=3, column=1, sticky=W)
label7.grid(row=3, column=2, sticky=E)
# Create and attach entries
self.voltage = Entry(root)
self.duration = Entry(root)
self.voltage.grid(row=0, column=1)
self.duration.grid(row=1, column=1)
# Create, bind, and attach buttons
HeatButton = Button(root, text='Heat')
HeatButton.bind("<Button-1>", self.Heat)
HeatButton.grid(row=0, column=2)
CoolButton = Button(root, text='Cool')
CoolButton.bind("<Button-1>", self.Heat)
CoolButton.grid(row=1, column=2)
StopButton = Button(root, text='Stop')
StopButton.bind("<Button-1>", self.Stop)
StopButton.grid(row=2, column=2)
def HeatLoop(self, condition, TimeStart, TimeDuration, MaximumVoltage, Fraction=0):
"""Heat up the cell while the condition is true"""
if condition:
self.percent.set("{:2.2f}%".format(Fraction * 100))
print(MaximumVoltage)
self.currentvoltage.set("Current Voltage: {:2.2f} V".format(Fraction*MaximumVoltage))
self.Update()
CurrentTime = self.DT.now()
ElapsedTime = (CurrentTime.second/3600 + CurrentTime.minute/60 + CurrentTime.hour
- TimeStart.second/3600 - TimeStart.minute/60 - TimeStart.hour)
Fraction = ElapsedTime / TimeDuration
print(Fraction)
self.root.after(5000)
self.HeatLoop(bool(not self.STOP and Fraction < 1),
TimeStart, TimeDuration, MaximumVoltage, Fraction)
# Define function to heat up cell
def Heat(self, event):
# Initialize Parameters
self.STOP = False
self.error.set("---")
self.Update()
# Try to get voltage and duration from the GUI
MaxVoltage = self.voltage.get()
TimeDuration = self.duration.get()
try:
MaxVoltage = float(MaxVoltage)
try:
TimeDuration = float(TimeDuration)
except:
self.error.set("Please enter a valid time duration")
self.Update()
self.STOP = True
except:
self.error.set("Please enter a valid voltage value")
self.Update()
self.STOP = True
TimeStart = self.DT.now()
self.HeatLoop(True,
TimeStart, TimeDuration, MaxVoltage)
def Stop(self, event):
self.STOP = True
print("turned off voltage")
def Update(self):
self.root.update_idletasks()
self.root.update()
root1 = Tk()
a = GUIClass(root1)
root1.mainloop()
root.after(5000) is no different than time.sleep(5). It's doing exactly what you're telling it to: to freeze for five seconds.
If you want to run self.HeatLoop every five seconds, the way to do it is like this:
self.root.after(5000, self.HeatLoop,
bool(not self.STOP and Fraction < 1),
TimeStart, TimeDuration, MaximumVoltage,
Fraction)
When you give two or more arguments to after, tkinter will add that function to a queue, and will call that function after the time has expired. This allows the event loop to continue to process events during the five second interval.
A slightly better way to write it would be to check for the condition inside the function rather than passing the condition in, so that the condition is evaluated immediately before doing the work rather than five seconds before doing the work.
For example:
def HeatLoop(self, TimeStart, TimeDuration, MaximumVoltage, Fraction=0):
if self.STOP and Fraction < 0:
return
...
self.root.after(5000, self.HeatLoop,
TimeStart, TimeDuration, MaximumVoltage,
Fraction)

Tkinter Grid Alignment Issue

I'm pretty new with tkinter and I can't figure why the q is not aligned near the Entry.
# String
self.user_p = StringVar()
self.user_q = StringVar()
self.user_r = StringVar()
self.user_result = StringVar()
# Label
self.description = Label(self.root, text="!p v (q ^ r)")
self.pLabel = Label(self.root, text="p")
self.qLabel = Label(self.root, text="q")
self.rLabel = Label(self.root, text="r")
self.resultLabel = Label(self.root, text="Result")
# Entry
self.p = Entry(self.root, textvariable = self.user_p, width = 10)
self.q = Entry(self.root, textvariable = self.user_q, width = 10)
self.r = Entry(self.root, textvariable = self.user_r, width = 10)
self.result = Entry(self.root, bg = "white", state=DISABLED, text = "")
# Grid
# Labels
self.description.grid(row = 0, column = 3, sticky = N)
self.pLabel.grid(row = 1, column = 0, sticky = E)
self.qLabel.grid(row = 1, column = 2, sticky = E)
self.rLabel.grid(row = 1, column = 4, sticky = E)
# Entry
self.p.grid(row=1, column=1)
self.q.grid(row = 1, column = 3)
self.r.grid(row=1, column=5)
(with or without the sticky it's still the same)
Here's a picture: http://imgur.com/a/wrOGa
The first part in the picture is what I'm getting right now. And the second part is what I want it to look like
Am I doing something wrong?
Welcome. I have taken the liberty to attach an example of a test code (see below). Please remember to do that in your post as mine can be different to yours. I did not encounter the issue you described. See attached picture. I am using python3.5 on Ubuntu 16.04.
One other thing, you can be more explicit by adding the option justify=RIGHT in your label widget commands to alight the label text to right.
from tkinter import *
class App(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, background='pink')
# String
self.user_p = StringVar()
self.user_q = StringVar()
self.user_r = StringVar()
self.user_result = StringVar()
# Label
self.description = Label(self, text="!p v (q ^ r)")
self.pLabel = Label(self, text="p")
self.qLabel = Label(self, text="q")
self.rLabel = Label(self, text="r")
self.resultLabel = Label(self, text="Result")
# Entry
self.p=Entry(self, textvariable=self.user_p, width=10)
self.q=Entry(self, textvariable=self.user_q, width=10)
self.r=Entry(self, textvariable=self.user_r, width=10)
self.result=Entry(self, bg="white", state=DISABLED, text="")
# Grid
# Labels
self.description.grid(row=0, column=3, sticky=N)
self.pLabel.grid(row=1, column=0, sticky=E)
self.qLabel.grid(row=1, column=2, sticky=E)
self.rLabel.grid(row=1, column=4, sticky=E)
# Entry
self.p.grid(row=1, column=1)
self.q.grid(row=1, column=3)
self.r.grid(row=1, column=5)
if __name__ == '__main__':
root=Tk()
root.geometry("300x50")
app=App(root)
app.pack(fill="both", expand=True)
app.mainloop()

Python - Tkinter - Label Not Updating

Any ideas why the leftresult_label label does not update? The function seems to work but the label does not update. I have looked everywhere and can't find an answer. The 'left' value gets set but the label does not change.
from tkinter import *
root = Tk(className="Page Calculator")
read = IntVar()
total = IntVar()
left = IntVar()
read.set(1)
total.set(1)
left.set(1)
read_label = Label(root,text="Pages Read:")
read_label.grid(column=1, row=1)
total_label = Label(root,text="Total Pages:")
total_label.grid(column=1, row=2)
read_entry = Entry(root,textvariable=read)
read_entry.grid(column=2, row=1)
total_entry = Entry(root,textvariable=total)
total_entry.grid(column=2, row=2)
def func1():
left.set(total.get() - read.get())
print(left.get())
calculate_button = Button(root,text="Calculate",command= func1)
calculate_button.grid(column=2, row=3)
percenet_label = Label(root,text="Percent Finished:")
percenet_label.grid(column=1, row=4)
left_label = Label(root,text="Pages Left:")
left_label.grid(column=1, row=5)
percenetresult_label = Label(root,text=left.get())
percenetresult_label.grid(column=2, row=4)
leftresult_label = Label(root,text="")
leftresult_label.grid(column=2, row=5)
root.mainloop()
To make the function do the job, you'd rather have your label:
leftresult_label = Label(root, textvariable=left)
Once it's tkinter class variable, tkinter takes care about when you change the value. Once you click the button,
def func1():
left.set(total.get() - read.get())
percent.set(int(read.get()*100/total.get()))
left and percent values, which are instances of tkinter.IntVar() class have immidiate effect on widgets (labels in this case) where those values are set as textvariable, just as you have it at Entry widgets.
Here is full code:
from tkinter import *
root = Tk(className="Page Calculator")
read = IntVar()
total = IntVar()
left = IntVar()
percent = IntVar()
read.set(1)
total.set(1)
left.set(1)
percent.set(1)
def func1():
left.set(total.get() - read.get())
percent.set(int(read.get()*100/total.get()))
read_label = Label(root,text="Pages Read:")
read_label.grid(column=1, row=1)
read_entry = Entry(root,textvariable=read)
read_entry.grid(column=2, row=1)
total_label = Label(root,text="Total Pages:")
total_label.grid(column=1, row=2)
total_entry = Entry(root,textvariable=total)
total_entry.grid(column=2, row=2)
calculate_button = Button(root,text="Calculate",command= func1)
calculate_button.grid(column=2, row=3)
percenet_label = Label(root,text="Percent Finished:")
percenet_label.grid(column=1, row=4)
left_label = Label(root,text="Pages Left:")
left_label.grid(column=1, row=5)
percenetresult_label = Label(root,textvariable=percent)
percenetresult_label.grid(column=2, row=4)
leftresult_label = Label(root,textvariable=left)
leftresult_label.grid(column=2, row=5)
root.mainloop()
code including progress bar. update_idletasks() used to keep label and progress bar running.
from tkinter import *
from tkinter import ttk
root = Tk()
root.title('Counter Test')
root.iconbitmap('IT.ico')
root.geometry("800x400")
def missing():
while i < 100:
progress1['value'] = i
label1.config(text=progress1['value'])
root.update_idletasks()
i += 1
progress1 = ttk.Progressbar(root, orient=HORIZONTAL, length=250, mode='determinate')
progress1.pack(pady=15)
label1 = Label(root, text="")
label1.pack(pady=15)
button_1 = Button(root, text="Missing", command=missing)
button_1.pack(pady=15)
button_q = Button(root, text="Quit", command=root.destroy)
button_q.pack(pady=15)
root.mainloop()
so to update controls immediately, like updating labels and TreeView elements this code worked for me.
window = tk.Tk()
window.update_idletasks()

How to get the value of the selected radio button?

I would like to create 2 different groups of radio buttons. The user would select one option from either group. There would be a function that would get the values(strings) from the selected radio buttons and then print them. Here's my code but it doesn't work (i'm new to python).
from tkinter import *
root = Tk()
btn1 = "lol"
btn2 = "lel"
def funkcija():
n = entry1.get()
m = "null"
X = btn1.get()
Y = btn2.get()
print("%s %s je %s %s." % (n, X, m, Y))
theLabel = Label(root, text="Vnesite količino in izberite prvo valuto.")
theLabel.grid(row=0, columnspan=3)
gumb1=Radiobutton(root,text="Euro",value = "euro",variable = "btn1").grid(row=2, column=1, sticky=W)
gumb2=Radiobutton(root,text="Dolar",value = "dolar",variable = "btn1").grid(row=3, column=1, sticky=W)
gumb3=Radiobutton(root,text="Funt",value = "funt",variable = "btn1").grid(row=4, column=1, sticky=W)
label3= Label(root, text="Izberite drugo valuto.")
label3.grid(row=6, columnspan=3)
label35= Label(root)
label35.grid(row=5, columnspan=3)
gumb4=Radiobutton(root,text="Euro",value = "euro",variable = "btn2").grid(row=7, column=1, sticky=W)
gumb5=Radiobutton(root,text="Dolar",value = "dolar",variable = "btn2").grid(row=8, column=1, sticky=W)
gumb6=Radiobutton(root,text="Funt",value = "funt",variable = "btn2").grid(row=9, column=1, sticky=W)
label1 = Label(root, text="Količina:")
label1.grid(row=1, sticky=E)
entry1 = Entry(root)
entry1.grid(row=1, column=1, sticky=W)
go = Button(root, text="Izračun", fg="white", bg="black", command=funkcija)
go.grid(row=10, columnspan=3)
root.mainloop()
In your radio button, analyze the parameters that you are passing:
gumb1 = Radiobutton(root,
text = "Euro",
value = "Euro",
variable = "btn2"
The parameters value and variable are what stores the data of the radio button. You've set your value option correctly. The interpreter will automatically set the variable with the value when the radio button is selected.
But here's where your issue is:
variable = "btn2"
"btn2" is a string. Not very useful though, is it? In fact, you're trying to perform methods on it that don't even exist. Such as here:
def funkcija():
X = btn2.get()
In fact, taking this information, you almost got there!
At the top of your script, you need to set btn2 to Tkinter's StringVar, like so:
from tkinter import *
btn1 = StringVar()
btn2 = StringVar()
Now that's done, let's change our parameters in our radio buttons.
gumb1 = Radiobutton(root,
text = "Euro",
value = "Euro",
variable = btn2
Now, Tkinter will automatically update the variable when it is selected. To get the value, do the same that you had done in your funkcija.
X = btn2.get()
And then the value of btn2 (which was updated by the radio buttons) will not be read, and stored into the variable X.

Categories

Resources