I am new in python GUI. I was trying to get the value from 'abc' entry box. However, it can only get the default value (which is 58 now). If I change the value then it cannot get the changed (or current) value. Your input would be highly appreciated.
fields = ('abc', 'def', 'ghi','jkl')
def outputdata(master, fields):
entries = {}
helpLf = LabelFrame(master, text="2. Bill of Materials:")
helpLf.grid(row=0, column=9, columnspan=5, rowspan=8, \
sticky='NS', padx=5, pady=5)
for n in range(len(fields)):
lab = Label(helpLf, text= fields[n]+": ", anchor='w')
lab.grid(row=n, column=5, padx=5, pady=5)
ent = Entry(helpLf, bg="yellow")
ent.insert(0,"58")
ent.grid(row=n, column=7, padx=5, pady=5)
entries[fields[n]] = ent
return entries
if __name__ == '__main__':
master = Tk()
ents = outputdata(master, fields)
t = outputdata(master, fields)['abc'].get()
Button(master, text='Show me the BoM', command = (lambda e=ents:clamp_number(e))).grid(row=10, column=0, sticky=W, pady=4)
Without knowing what clamp_number is, I cannot comment on your code in particular.
But, if you want to know how to get the "current" value of a Entry widget, you will have to use a StringVar variable.
>>> from tkinter import Tk, StringVar, Entry
>>> root = Tk()
>>> sv = StringVar(root)
>>> entry = Entry(root, textvariable=sv)
>>> sv.get()
''
>>> entry.insert('insert', 'hello')
>>> sv.get()
'hello'
>>>
Whats happening here is, you are binding an Entry widget to a StringVar. You can call the StringVar's get() and set() methods as required.
Related
I need to take a value from user and then pass this value into function to get a string with this values. My code in first file looks like below (of course it is simplified version):
import tkinter as tk
from tkinter import ttk
import myfunction # this is my module that has another function
class Interface(ttk.Frame):
def __init__(self, container):
super().__init__(container)
self.user_price_minimum = tk.StringVar()
minimum_price = ttk.Label(self, text="Minimum price is: ")
minimum_price.grid(row=0, column=0, padx=5, pady=5)
minimum_price_entry = ttk.Entry(self, width=15, textvariable = self.user_price_minimum)
minimum_price_entry.grid(row=0, column=1)
minimum_price_entry.focus()
#############
button = ttk.Button(self, text="Use price")
button.grid(column=0, rows=2, columnspan=2, padx=5, pady=5)
root = tk.Tk()
root.geometry("450x250")
root.title("Looking for a flat")
root.columnconfigure(0, weight=1)
frame = Interface(root)
frame.pack()
root.mainloop()
My another python file that calls myfunction.py should be able to take this minimum_price from user and add this into string. Code looks like below:
def minimum_price(self):
price_min = self.user_price_minimum.get()
price_min = int(price_min)
print(f'Minimum price is: {price_min}')
So I am not sure how I could use minimum_price values from user into this function.
The simplest is to do this:
button = ttk.Button(self, text="Use price", command=lambda: myfunction.minimum_price(self))
However you could also define it as a method in the class itself:
class Interface(ttk.Frame):
def __init__(self, container):
super().__init__(container)
self.user_price_minimum = tk.StringVar()
minimum_price = ttk.Label(self, text="Minimum price is: ")
minimum_price.grid(row=0, column=0, padx=5, pady=5)
minimum_price_entry = ttk.Entry(self, width=15, textvariable = self.user_price_minimum)
minimum_price_entry.grid(row=0, column=1)
minimum_price_entry.focus()
#############
button = ttk.Button(self, text="Use price", command=self.print_price)
button.grid(column=0, rows=2, columnspan=2, padx=5, pady=5)
def print_price(self):
price = self.user_price_minimum.get()
print(f'Minimum price: {price}')
My personal preference (when using another file in such a case like this one (tho I would probably prefer to define this as above)) would be if:
# in the other file
def minimum_price(value):
print(f'Minimum price: {value}')
# inside the class
button = ttk.Button(self, text="Use price", command=lambda: myfunction.minimum_price(self.user_price_minimum.get()))
Also in this case you don't necessarily need the StringVar, you could also simply get the value by using:
# assignment
self.minimum_price_entry = ttk.Entry(self, width=15)
# get value (probably in some function call, basically the same way as with the `StringVar` except less code)
self.minimum_price_entry.get()
I have only been programming 3 months so any advice on improvement to my code is appreciated even if it inst related to my specific question.
Its a simple small project with tkinter. Two fields to enter your first and last name then you hit the swap button and it will swap what ever you put in the name fields.
Problem is I dont want to use globals and I cant seem to figure it out I know its probably something easy and I did spend time trying to figure it out.
If you have any improvements to the code let me know.
from tkinter import *
### I dont Want Globals but cant figure out another method for doing this
### Hope some one can help me with this part
evar = ""
evar1 = ""
def mainWindow():
root = Tk()
root.title("Swap Names")
root.geometry("400x150+100+250")
return root
def createVar():
global evar
global evar1
evar = StringVar()
evar1 = StringVar()
def firstNameFrame(root):
frame1 = Frame(root)
frame1.pack(side=TOP, padx=2, pady=2)
label = Label(frame1, text="First Name:")
label.pack(side=LEFT, padx=2, pady=2)
entry = Entry(frame1, textvariable = evar)
entry.pack(side=LEFT, pady = 2)
def lastNameFrame(root):
frame2 = Frame(root)
frame2.pack(side=TOP, padx=2, pady=2)
label = Label(frame2, text="Last Name:")
label.pack(side=LEFT, padx=1, pady=1)
entry = Entry(frame2, textvariable = evar1)
entry.pack(side=LEFT, pady = 5)
def swapFrame(root):
frame3 = Frame(root)
frame3.pack(side=TOP, padx=10, pady = 10)
swapButton = Button(frame3, text="Swap",command = swap)
swapButton.pack(side=LEFT, padx =5, pady=5)
### I would like to some how use swap with out using a global
def swap():
b=evar.get()
evar.set(evar1.get())
evar1.set(b)
def main():
root = mainWindow()
createVar()
firstNameFrame(root)
lastNameFrame(root)
swapFrame(root)
root.mainloop()
main()
One of the solutions can be wrapping all the code related to the initialization and working with Tk in a separate class, so instead of global variables, we will use the class instance variables:
from tkinter import *
class Gui(object):
def __init__(self):
self.root = Gui._init_main_window()
self.first_name_var = StringVar()
self.last_name_var = StringVar()
self._init_first_name_frame()
self._init_last_name_frame()
self._init_swap_frame()
#staticmethod
def _init_main_window():
root = Tk()
root.title("Swap Names")
root.geometry("400x150+100+250")
return root
def _init_first_name_frame(self):
frame1 = Frame(self.root)
frame1.pack(side=TOP, padx=2, pady=2)
label = Label(frame1, text="First Name:")
label.pack(side=LEFT, padx=2, pady=2)
entry = Entry(frame1, textvariable=self.first_name_var)
entry.pack(side=LEFT, pady=2)
def _init_last_name_frame(self):
frame2 = Frame(self.root)
frame2.pack(side=TOP, padx=2, pady=2)
label = Label(frame2, text="Last Name:")
label.pack(side=LEFT, padx=1, pady=1)
entry = Entry(frame2, textvariable=self.last_name_var)
entry.pack(side=LEFT, pady=5)
def _init_swap_frame(self):
frame3 = Frame(self.root)
frame3.pack(side=TOP, padx=10, pady=10)
swap_button = Button(frame3, text="Swap", command=self._swap)
swap_button.pack(side=LEFT, padx=5, pady=5)
def _swap(self):
tmp = self.first_name_var.get()
self.first_name_var.set(self.last_name_var.get())
self.last_name_var.set(tmp)
def mainloop(self):
return self.root.mainloop()
def main():
gui = Gui()
gui.mainloop()
if __name__ == '__main__':
main()
A small comment to the code above: adding a prefix __ to variables or methods allows you to hide access to them directly by name outside the class using the name mangling.
UPD: According to #Coal comment, changed the double underscore prefixes to single underscore, as there is no need to use a name mangling.
This is assuming that when you say you don't want to use global, that you also mean that you don't want to use self:
from tkinter import Tk, Button, Entry
def swap(fn, ln):
# Get the contents of the two fields.
first = fn.get()
last = ln.get()
# Clear the contents of both fields.
first_name.delete(0, 'end')
last_name.delete(0, 'end')
# Set each field to the previous content of the other field.
first_name.insert(0, last)
last_name.insert(0, first)
root = Tk()
first_name = Entry(root)
last_name = Entry(root)
first_name.insert(0, "Enter first name")
last_name.insert(0, "Enter last name")
first_name.pack()
last_name.pack()
swap_button = Button(root, text="SWAP", command=lambda:swap(first_name, last_name))
swap_button.pack()
root.mainloop()
I got a piece of code and I want to change it for my project, but I don't know how to get the value of my entries has a variable to be used in the start function. Here is my code:
#!/usr/bin/python3
import wiringpi
from time import sleep
gpio = wiringpi.GPIO(wiringpi.GPIO.WPI_MODE_GPIO)
shutterpin = 17
flashpin = 18
solenoidpin = 22
gpio.pinMode(shutterpin,gpio.OUTPUT)
gpio.pinMode(flashpin,gpio.OUTPUT)
gpio.pinMode(solenoidpin,gpio.OUTPUT)
wiringpi.pinMode(shutterpin,1)
wiringpi.pinMode(flashpin,1)
wiringpi.pinMode(solenoidpin,1)
from Tkinter import *
fields = 'size_drop1', 'interval_drop', 'size_drop2', 'lapse_before_flash', 'shutter_time'
def fetch(entries):
for entry in entries:
field = entry[0]
text = entry[1].get()
print('%s: "%s"' % (field, text))
def start(entries):
size_drop1 : float(size_drop1)
interval_drop : float(interval_drop)
size_drop2 : float(size_drop2)
lapse_before_flash : float(lapse_before_flash)
shutter_time : float(shutter_time)
sleep(lapse_before_flash)
gpio.digitalWrite(shutterpin,gpio.HIGH)
sleep(0.5)
gpio.digitalWrite(shutterpin,gpio.LOW)
gpio.digitalWrite(solenoidpin,gpio.HIGH)
sleep(size_drop1)
gpio.digitalWrite(solenoidpin,gpio.LOW)
gpio.digitalWrite(solenoidpin,gpio.HIGH)
sleep(interval_drop)
gpio.digitalWrite(solenoidpin,gpio.LOW)
gpio.digitalWrite(solenoidpin,gpio.HIGH)
sleep(size_drop2)
gpio.digitalWrite(solenoidpin,gpio.LOW)
sleep(lapse_before_flash)
gpio.digitalWrite(flashpin,gpio.HIGH)
sleep(0.5)
gpio.digitalWrite(flashpin,gpio.LOW)
def makeform(root, fields):
entries = []
for field in fields:
row = Frame(root)
lab = Label(row, width=15, text=field, anchor='w')
ent = Entry(row)
row.pack(side=TOP, fill=X, padx=5, pady=5)
lab.pack(side=LEFT)
ent.pack(side=RIGHT, expand=YES, fill=X)
entries.append((field, ent))
return entries
if __name__ == '__main__':
root = Tk()
ents = makeform(root, fields)
root.bind('<Return>', (lambda event, e=ents: fetch(e)))
b1 = Button(root, text='Show',
command=(lambda e=ents: fetch(e)))
b1.pack(side=LEFT, padx=5, pady=5)
b2 = Button(root, text='start', command=(lambda e=ents: start(e)))
b2.pack(side=LEFT, padx=5, pady=5)
b3 = Button(root, text='Quit', command=root.quit)
b3.pack(side=LEFT, padx=5, pady=5)
root.mainloop()
You seem to have the right idea on the fetch function part of your code, to access the typed text in a Entry Box on Tkinter, you can use the .get() function, like so:
# main tk window
root = Tk()
# creates the entry_box
entry_box = Entry(root, text='')
# places the entry_box on the program
entry_box.grid()
# changes the text, starting on the first char of the entry_box to 'test'
# (for testing purposes)
entry_box.insert(0, 'test')
# prints the typed test, in this case 'test'
print(entry_box.get())
# run the program
mainloop()
This will print the inserted string, just so you get the hang of it.
Also remember to assign the Entry to a variable, so you can call the .get() function.
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.
I've been trying to get my Tkinter dialog to do a simple date subtraction, but something is holding it up. The date subtraction seems to hold up when run from the shell, but I'm getting nothing from this is Tk.
The code is borrowed from another script that I have running successfully with all the form and windows setup.
#!/usr/bin/python
from Tkinter import *
import datetime
import math
fields = ('Enter Date (mm/dd/yy)', 'Days Since 10/30/14')
def Calc(entries):
d = raw_input(entries['Enter Date (mm/dd/yy)'].get())
nd = datetime.datetime.strptime(d, "%m/%d/%y").date()
d1 = "10/30/14"
od = datetime.datetime.strptime(d1, "%m/%d/%y").date()
diff = (nd - od).days
diff = ('%8.2f' % diff).strip()
entries['Days Since 10/30/14'].delete(0,END)
entries['Days Since 10/30/14'].insert(0, diff)
def makeform(root, fields):
root.title('Date Difference')
entries = {}
for field in fields:
row = Frame(root)
lab = Label(row, width=22, text=field+": ", anchor='w', font=('arial', 12))
ent = Entry(row, font=('arial', 12))
row.pack(side=TOP, fill=X, padx=5, pady=5)
lab.pack(side=LEFT, padx=10)
ent.pack(side=RIGHT, expand=YES, fill=X)
entries[field] = ent
return entries
if __name__ == '__main__':
root = Tk()
root.geometry("400x400+300+300")
ents = makeform(root, fields)
root.bind('<Return>', (lambda event, e=ents: Calc(e)))
b1 = Button(root, text='Calculate', font=('arial',12), command=(lambda e=ents: Calc(e)))
b1.pack(side=LEFT, padx=5, pady=5)
b2 = Button(root, text='Quit', font=('arial',12), command=root.quit)
b2.pack(side=LEFT, padx=5, pady=5)
root.mainloop()
Any help would be appreciated...
Even now I messed it up more, somehow it doesn't even start at all and highlights the "lab" variable under makeform(root,fields): it was running a minute ago, though would not do the calculation...
Help?
d = raw_input(entries['Enter Date (mm/dd/yy)'].get())
raw_input gets data from the user via the command line. Is that intentional? You don't need it if you just want to find what the user typed into the entry.
d = entries['Enter Date (mm/dd/yy)'].get()