Tkinter - Iterating default text entry - python

I'm trying to create a GUI which will enable me to create folders with iterating names each time I click a button, i.e. 'folder_1', 'folder_2, 'folder_3',... which is isn't too difficult.
But, I also want the ability to manually change the number at which the iteration starts: I can enter '10' in an entry box and click the button, which would create 'folder_10' and each time I click the button after that it would continue to iterate, i.e folder_11, folder_12, folder_13,...
It would also be very helpful if the entry box contained the number of the next folder, as a default (that I can change manually), to be created when I click the button.
I've been trying to get something like this to work but no luck:
from tkinter import *
master = Tk()
master.counter = 0
def create_folder():
newfoldername = 'Folder_'+e1.get()+'/'
master.counter += 1
print(newfoldername)
#...folder creation here (I know how to do this...)
e1 = Entry(master)
e1.insert(0, master.counter)
e1.grid(row=0, column=1)
Button(master, text='Create folder', command=create_folder).grid(row=1,
column=1)
mainloop()
I am newbie to python so this might be really simple...
Thanks.

I would recommend you use IntVar()(If you type string in the Entry and use .get(),you will get error.) or StringVar().
from tkinter import *
master = Tk()
master.counter = IntVar()
master.counter.set(0)
def create_folder():
newfoldername = 'Folder_'+str(master.counter.get())+'/'
master.counter.set(master.counter.get()+1)
print(newfoldername)
#...folder creation here (I know how to do this...)
e1 = Entry(master, textvariable=master.counter)
e1.grid(row=0, column=1)
Button(master, text='Create folder', command=create_folder).grid(row=1,
column=1)
mainloop()

Shows the next value in the Entry box and creates directory with that number. If you change the value in the Entry box, it continues from there.
from tkinter import *
master = Tk()
master.counter = 0
def create_folder():
newfoldername = 'Folder_'+e1.get()+'/'
master.counter = int(e1.get())
master.counter += 1
e1.delete(0, END)
e1.insert(0, str(master.counter))
print(newfoldername)
#...folder creation here (I know how to do this...)
e1 = Entry(master)
e1.insert(0, master.counter)
e1.grid(row=0, column=1)
Button(master, text='Create folder', command=create_folder).grid(row=1,
column=1)
mainloop()

Related

tkinter TextVar.get() returns '.!entry' not a string

I have the below code which for some reason when i call .get() to the textvariable on tkinter.Entry, I get '.!entry' instead of the string I am expecting. How can I fix this?
def getter():
final = e1str_var.get()
e1str_var = StringVar()
e1 = Entry(root, textvar=e1str_var)
e1.grid(row=4, column=0)
print(getter())
Returns '.!entry'
Your question seems unclear, you will be able to use get() of an Entry field on a certain action like a button click.
In the below code I made a button as well and when you click this button you will get what is written inside the textbox as your output.
from tkinter import *
def helloCallBack():
print(E1.get())
top = Tk()
L1 = Label(top, text="User Name")
L2 = Button(top, text="Click",command = helloCallBack)
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)
L2.pack(side = BOTTOM)
print(E1.get())
top.mainloop()
You can only get the string in a text box when perfomed some event like button click or binding label or some other widget with an event. Here I have used a button for using get().
from tkinter import *
root=Tk()
def getter():
final = e1str_var.get()
print(final)
e1str_var = StringVar()
e1 = Entry(root, textvar=e1str_var)
b1=Button(root,text="Click",command=getter)
e1.grid(row=4, column=0)
b1.grid(row=5,column=0)
root.mainloop()

How to correct the output from an entry box

When using the feeder button, the script for F runs through entirely through to the print before the 'master' box appears, then does not react to the inputs from the 'master' box. This results in the output being 0.0 kW because the input is a long decimals followed by an L, when what I, the user inputs is 8777
I have been roaming the internet for about a day now with no luck finding anything. I am very new to TK but have been trying to learn it.
def F():
master = tk.Tk()
tk.Label(master, text = 'Feeder Number: ').grid(row=0)
entry1 = tk.Entry(master)
entry1.grid(row=0, column=1)
button2 = tk.Button(master,
text=' Confirm',
command=entry1.get())
button2.pack()
button2.grid(row=0, column=2)
fn = entry1.pack()
print fn
feed = filtered['Feeder']==fn
feedfn = filtered[feed]
Cap = feedfn['AC Name Plate Capacity <= 10kw']
Cap = Cap.astype(float)
AcPv = Cap.sum()
print 'The total PV on this feeder is:', AcPv, 'kW'
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
button = tk.Button(frame,
text='Exit',
fg='red',
command=quit)
button.pack()
button.grid(row=1, column=1)
Fee = tk.Button(frame,
text='Feeder',
command=F)
Fee.pack()
Fee.grid(row=0, column=1)
root.mainloop()
Expected 27.702
Output 0.0
Given that I will not be posting the csv,
entry1/fn should be 8777
currently 'none'
UPDATE
I am now receiving an output of PY_VAR when printing fn, I understand that the code is running all the way through before taking an input. Any recommendations for how to take the input before the filters are run?
def F():
master = tk.Tk()
tk.Label(master, text = 'Feeder Number: ').grid(row=0)
entry1 = tk.Entry(master)
entry1.grid(row=0, column=1)
button2 = tk.Button(master,
text=' Confirm',
command=entry1.get())
button2.grid(row=0, column=2)
fn = tk.IntVar()
print fn
feed = filtered['Feeder']==fn
feedfn = filtered[feed]
Cap = feedfn['AC Name Plate Capacity <= 10kw']
Cap = Cap.astype(float)
AcPv = Cap.sum()
print 'The total PV on this feeder is:', AcPv, 'kW'
For those interested in the final code (Which worked for me):
def F():
master = tk.Tk()
tk.Label(master, text = 'Feeder Number: ').grid(row=0)
entry = tk.Entry(master)
entry.grid(row=0, column=1)
def pint():
data = entry.get()
master.destroy()
feed = filtered['Feeder']==data
feedfn = filtered[feed]
Cap = feedfn['AC Name Plate Capacity <= 10kw']
Cap = Cap.astype(float)
AcPv = Cap.sum()
fdf = tk.Tk()
tk.Label(fdf, text = AcPv).grid(row=0)
button4 = tk.Button(fdf,
text = ' Exit',
fg='red',
command=fdf.destroy)
button4.grid(row=1)
button2 = tk.Button(master,
text=' Confirm',
command = pint)
button2.grid(row=0, column=2)
button3 = tk.Button(master,
text = ' Exit',
fg='red',
command=master.destroy)
button3.grid(row=0, column=3)
master.mainloop()
There a few mistake in your code that lead to the different output you have received.
First, why is your code executing without showing the master box :
Your tkinter need a mainloop() call if you want a persistent window.
master.mainloop()
You did that right with your root, but your master lacks that mainloop. This line is what basically keeping your GUI alive and looping over it for changes until it is destroyed one way or another. You need to add this line after creating your widgets in order to be able to interact with the window. Anything written after this line (but still indented in the definition) will be executed when your window is closed, either manually or with the command :
master.destroy()
Next, although this will yield a working window, you can still interact with your root window while the master window is up, which can lead to problems if you are expecting variable from master. I suggest you read about the Toplevel widget which is made specifically for cases like yours. (http://effbot.org/tkinterbook/toplevel.htm) Alternatively, you could also use tkinter's tkSimpleDialog.askinteger or askfloat functions which seems perfect for your application.
Finally, the entry allows you to write text but how to access the text? you can use Entry1.get() to extract the content of the entry, or as you have started to to in your update, you can assign a tkinter variable to the entry. This variable will be updated as you change write strings or numbers in the entry. To bind the variable to your entry, you must state it in the entry's creation :
fn = tk.StringVar(value = '000')
entry1 = tk.Entry(master, textvariable = fn)
*Note, this will require your fn variable to be initialized before the entry. Also, you can initialize a value for that variable upon creation
the tkinter variable is an object which is why when you print it, you get PY_VAR. (the type of object) To access the value, you need to use the get() method :
print(fn.get())

iPython: How to get 3 variables from user

I've got a problem. I have to write program, that check what was day of the week of given DAY, MONTH, YEAR.
I defined a function 'dayoftheweek' which finds day of the week of given date.
But here is my problem. I don't know how to get three variables d,m,y from user with GUI.
Also I don't know how to make a fine button saying "Accept" and will move my 3 variables into dayoftheweek function.
Here is the code
import math
from tkinter import *
def dayoftheweek(d, m, y):
a=math.floor((14-m)/12)
y1=r+4800-a
n=m+12*-3
l=d+math.floor((153*n)/5)+365*y1+math.floor(y1/4)-math.floor(y1/100)+math.floor(y1/100)-32045
p = (l%7)+1
return p
def date():
d = int(e1.get())
m = int(e2.get())
y = int(e3.get())
print(dayoftheweek(d, m, y))
master = Tk()
Label(master, text="Day").grid(row=0)
Label(master, text="Month").grid(row=1)
Label(master, text="Year").grid(row=2)
e1 = Entry(master)
e2 = Entry(master)
e3 = Entry(master)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
mainloop( )
To print something in Tkinter, you can't just use print statement in your code.
You have to have a Label somewhere, and then change the contents of that Label. To do that you have to have a StringVar assigned to that Label. A StringVar is like a special case of normal strings, special because everytime it changes it will refresh how your window looks. That's what I did here:
printVar = StringVar()
Label(master, textvariable=printVar).grid(row=4, column=1)
Just added a Label in which we can update some text, aka "print to".
Additionally I added a Button, so that you could call your function date. You can make the window do something by using buttons that call assigned commands, or by binding keys (i.e. Enter, Space...) to the window.
button = Button(master, text="Ok", command=date).grid(row=3, column=1))
Now everytime you press your button the function date will be called, and the content of printVar will be changed and displayed in the Label.
Here's the full code, I also added the r=100 because your code is incomplete and gives the error that global r is not defined.
import math
from Tkinter import *
def dayoftheweek(d, m, y):
r = 100
a=math.floor((14-m)/12)
y1=r+4800-a
n=m+12*-3
l=d+math.floor((153*n)/5)+365*y1+math.floor(y1/4)-math.floor(y1/100)+math.floor(y1/100)-32045
p = (l%7)+1
return p
def date():
d = int(e1.get())
m = int(e2.get())
y = int(e3.get())
printVar.set(dayoftheweek(d, m, y))
master = Tk()
Label(master, text="Day").grid(row=0, column=0)
Label(master, text="Month").grid(row=1, column=0)
Label(master, text="Year").grid(row=2, column=0)
e1 = Entry(master)
e2 = Entry(master)
e3 = Entry(master)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
printVar = StringVar()
Label(master, textvariable=printVar).grid(row=4, column=1)
button = Button(master, text="Ok", command=date).grid(row=3, column=1)
mainloop( )

Trying to change label using entry box and button

I'm trying to make a label that will change when I enter text into the entry box and click the button.
I've tried doing some research but can't seem to find out how to do it .
from tkinter import *
master = Tk()
master.title("Part 3")
v = StringVar()
v.set("Please change me")
lb= Label(master, textvariable=v, fg="red",bg="black").grid(row=0,column=0)
ent= Entry(master, textvariable=v,).grid(row=1,column=2)
b1= Button(master, text="Click to change", fg="red",bg="black").grid(row=1,column=0)
to do so, you first need to define a callback that changes the value. (example below)
You should also use two Variables of type StringVar to store the different Values
from tkinter import *
master = Tk()
master.title("Part 3")
lText = StringVar()
lText.set("Please change me")
eText = StringVar()
def ChangeLabelText(event=None):
global lText
global eText
lText.set(eText.get())
Then, bind the callback to the button
lb = Label(master, textvariable=lText, fg="red",bg="black").grid(row=0,column=0)
ent = Entry(master, textvariable=eText).grid(row=1,column=2)
b1 = Button(master, text="Click to change", fg="red",bg="black", command=ChangeLabelText).grid(row=1,column=0)

Why is Tkinter Entry's get function returning nothing?

I'm trying to use an Entry field to get manual input, and then work with that data.
All sources I've found claim I should use the get() function, but I haven't found a simple working mini example yet, and I can't get it to work.
I hope someone can tel me what I'm doing wrong. Here's a mini file:
from tkinter import *
master = Tk()
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
content = entry.get()
print(content) # does not work
mainloop()
This gives me an Entry field I can type in, but I can't do anything with the data once it's typed in.
I suspect my code doesn't work because initially, entry is empty. But then how do I access input data once it has been typed in?
It looks like you may be confused as to when commands are run. In your example, you are calling the get method before the GUI has a chance to be displayed on the screen (which happens after you call mainloop.
Try adding a button that calls the get method. This is much easier if you write your application as a class. For example:
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.entry = tk.Entry(self)
self.button = tk.Button(self, text="Get", command=self.on_button)
self.button.pack()
self.entry.pack()
def on_button(self):
print(self.entry.get())
app = SampleApp()
app.mainloop()
Run the program, type into the entry widget, then click on the button.
You could also use a StringVar variable, even if it's not strictly necessary:
v = StringVar()
e = Entry(master, textvariable=v)
e.pack()
v.set("a default value")
s = v.get()
For more information, see this page on effbot.org.
A simple example without classes:
from tkinter import *
master = Tk()
# Create this method before you create the entry
def return_entry(en):
"""Gets and prints the content of the entry"""
content = entry.get()
print(content)
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
# Connect the entry with the return button
entry.bind('<Return>', return_entry)
mainloop()
*
master = Tk()
entryb1 = StringVar
Label(master, text="Input: ").grid(row=0, sticky=W)
Entry(master, textvariable=entryb1).grid(row=1, column=1)
b1 = Button(master, text="continue", command=print_content)
b1.grid(row=2, column=1)
def print_content():
global entryb1
content = entryb1.get()
print(content)
master.mainloop()
What you did wrong was not put it inside a Define function then you hadn't used the .get function with the textvariable you had set.
you need to put a textvariable in it, so you can use set() and get() method :
var=StringVar()
x= Entry (root,textvariable=var)
Most of the answers I found only showed how to do it with tkinter as tk. This was a problem for me as my program was 300 lines long with tons of other labels and buttons, and I would have had to change a lot of it.
Here's a way to do it without importing tkinter as tk or using StringVars. I modified the original mini program by:
making it a class
adding a button and an extra method.
This program opens up a tkinter window with an entry box and an "Enter" button. Clicking the Enter button prints whatever is in the entry box.
from tkinter import *
class mini():
def __init__(self):
master = Tk()
Label(master, text="Input: ").grid(row=0, sticky=W)
Button(master, text='Enter', command=self.get_content).grid(row=1)
self.entry = Entry(master)
self.entry.grid(row=0, column=1)
master.mainloop()
def get_content(self):
content = self.entry.get()
print(content)
m = mini()

Categories

Resources