I am trying to get user input using a Toplevel widget in order to create an order but the submit button does not work as expected please assist.
def spawn_window(self):
top = Toplevel()
top.title("Available Electronics")
self.entrytext = StringVar()
Entry(top, textvariable=self.entrytext).pack()
button = Button(top, text="Dismiss", command=top.destroy)
button.pack(side='right')
submit = Button(top, text ="Submit", command = self.datainput)
submit.pack(side='left')
def datainput(self):
input_var = self.entrytext.get()
self.devices.append(input_var)
"wanted the text box to turn blank as soon as the submit button was clicked in order to create room for another entry" now its clear what you really want!
In your datainput-method just clear your stringvar at the end, like this:
def datainput(self):
input_var = self.entrytext.get()
self.devices.append(input_var)
self.entrytext.set("")
Related
This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 2 years ago.
So i am trying to get an text input for my program but tkinter doesn't seem to register it,
and i don't know what i have done wrong
window = self.newWindow(value)
label = tk.Label(window, text="Intfix to Postfix Convert")
label.place(x=0, y=20)
e1 = tk.Entry(window)
text = e1.get()
e1.place(x=0, y=50)
rezultat = tk.Text(window, width=20, height=3)
rezultat.place(x=0, y=80)
button = tk.Button(window, text="Enter")
button.place(x=127, y=46)
button.bind("<Double-Button-1>", self.passValue(rezultat, text))
My code looks something like this. Everything else is working the self.newWindow(value) is just
a function that creates a new window from the main one
so i said text=e1.get() but i ran the debbuger and it says it is an empty string and i want to pass this text through the function passValue()(a function that passes the value to the controller), i used button.bind() to do that. Is that ok?
I tested it by putting a default value at text like text="My name" and it did pass the value so that should be in order but i don't know why doesn't it get it from the entry box like it should.
I even tried to do e1.insert(0,"some random thing") and text= e1.get() and it did get it so i think there's a problem with the input.
Do i need to use some special kind of input function?
The whole code:
class Gui:
def __init__(self, controller):
self.main = tk.Tk()
self.main.title("DSA Quiz Helper")
self.__controller = controller
def IntFixPostExecute(self, event):
widget = event.widget
selection = widget.curselection()
value = widget.get(selection[0])
self.IntfixPostfixWindow(value)
def mainWindow(self):
self.main.geometry("800x500")
# to do scrollbar
lb = tk.Listbox(self.main, width=50, height=30)
lb.insert(1, "Intfix and Postfix Calculator")
lb.insert(2, "Something else")
lb.bind("<Double-Button-1>", self.IntFixPostExecute)
lb.pack()
def IntfixPostfixWindow(self, value):
window = self.newWindow(value)
label = tk.Label(window, text="Intfix to Postfix Convert")
label.place(x=0, y=20)
e1 = tk.Entry(window)
text = e1.get()
e1.place(x=0, y=50)
rezultat = tk.Text(window, width=20, height=3)
rezultat.place(x=0, y=80)
button = tk.Button(window, text="Enter")
button.place(x=127, y=46)
button.bind("<Double-Button-1>", self.passValue(rezultat, text))
print(text)
def passValue(self, rezultat, value):
returnValue = self.__controller.InfixToPostC(rezultat, value)
rezultat.insert(tk.INSERT, returnValue)
def newWindow(self, msg):
newwind = tk.Toplevel(self.main)
q1 = tk.Frame(newwind)
q1.pack()
newwind.geometry("500x230")
return newwind
def run(self):
self.mainWindow()
self.main.mainloop()
if i set this manually it works. I don't understand why i doesn't work from entrybox input
text = tk.StringVar()
e1 = tk.Entry(window, textvariable=text)
text.set("x+y*2")
text = e1.get()
e1.place(x=0, y=50)
I think i figured it out (correct me if i am wrong). I think there is a problem
with the button because as soon as a newwindow is open, the button automatically clicks itself, when at first in the entry box there is no text written yet(so it sends to the controller with the initial text(which is empty)). The problem is why the button auto-clicks itself( or anyway auto-runs the function passValue) and why after i input the text and click the button again it does nothing(so as i understand it works only one time and auto-runs itself, at first there is no text in entrybox and the button auto-runs itself,therefore passing an empty string
You should use entryname.get() to get the text that is inside that entry instead of declaring stringVar() and making that much more unreadable and hard to comprehend and to work with. But this is my point of view! – Tiago Oliveira 48 mins ago
I think what is happening is that u use the method right after declaring the entry widget wich means u are going to get a "" empty string because that's nothing that was written there, u need to replace on the command parameter with entryname.get() instead of declaring variable = entryname.get() and passing that as parameter wich will always be empty! Hope this helps!
Working on a project in which I use Tkinter in order to create a GUI that gives a list of software in a drop-down and when a particular software is chosen, it takes you to a separate window where a user's name will be entered and they would be added to a database. With the code I have so far, I am able to link a "submit" button on the second window to a function that prints a confirmation message as a test to make sure the button works. My issue now is trying to get the input from the entry field and link the input to the "Submit" button but I can't seem to find a way to do so. I was wondering if I could get some advice on how to go about this. Would classes need to be used in order to make it work? or can I stick with functions and keep the code relatively simple?
I have added the code for my program below.
import tkinter as tk
from tkinter import *
from tkinter import ttk
root = tk.Tk() # Main window
root.title("Software Licences")
root.geometry("300x300")
frame = ttk.Frame(root, padding="50 0 50 50")
frame.pack(fill=tk.BOTH, expand=True)
tkvar = StringVar()
choices = ['Imagenow', # Dropdown menu with software options
'FileMakerPro',
'Acrobat',
'Office',
'Lotus Notes']
tkvar.set('Acrobat') # Shows default dropdown menu option when program is opened
popupMenu = OptionMenu(frame, tkvar, *sorted(choices))
popupLabel = ttk.Label(frame, text="Choose Software")
popupLabel.pack()
popupMenu.pack()
def software_pages(): # In this function is the 2nd window with for each individual software
top = Toplevel()
top.title("Software Licences")
top.geometry("300x300")
myLabel = Label(top, text=tkvar.get()).pack()
employee_entrylbl = Label(top, text="Employee name").pack()
employee_entry = Entry(top, width=25, textvariable=tk.StringVar) # Entry field for adding user's name
employee_entry.pack() # Entry field is displayed
if tkvar.get() == "Acrobat": # for each if statement, button command is link to the functions
# defined below
button = ttk.Button(top, text="Submit", command=add_to_acrobat).pack()
elif tkvar.get() == "Imagenow":
button = ttk.Button(top, text="Submit", command=add_to_imagenow).pack()
elif tkvar.get() == "FileMakerPro":
button = ttk.Button(top, text="Submit", command=add_to_filemakerpro).pack()
elif tkvar.get() == "Office":
button = ttk.Button(top, text="Submit", command=add_to_office).pack()
else:
button = ttk.Button(top, text="Submit", command=add_to_lotusnotes).pack()
exit_button = ttk.Button(top, text="Exit", command=top.destroy).pack() # Exit button for second window
add_emp_button = ttk.Button(frame, text="Next", command=software_pages) # "Next" button in the main window takes the
# user to the second window
add_emp_button.pack()
# Functions below are linked to the button commands of each software in the second window function defined earlier.
# They print out specified messages that confirm the user had been added
def add_to_acrobat():
return print("User added to Acrobat")
def add_to_lotusnotes():
print("User added to IBM")
def add_to_imagenow():
print("User added to imagenow")
def add_to_office():
print("User added to 365")
def add_to_filemakerpro():
print("User added to FMP")
def click_button(): # Function for Exit button for main window
root.destroy()
exit_button = ttk.Button(frame, text="Exit", command=click_button) # Exit button for main window
exit_button.pack()
root.mainloop()
You can pass parameters to the command of tkinter.command using partial from the functools module.
in your case:
button = ttk.Button(top, text="Submit", command=partial(add_to_acrobat, employee_entry)).pack()
in the above line, I send the employee_entry(Which holds your desired text) to the add_to_acrobat function
and the add_acrobat function should look like this:
def add_to_acrobat(e):
print(e.get())
return print("User added to Acrobat")
Hope it helps
I've got some code that opens a textbox so the user can input an EAN and then it scrapes the web. It all works fine except for some reason a mysterious second textbox opens with the original one and unless you use that one to close the program, it stops responding.
class MyDialog:
def __init__(self, parent): #Pop-up textbox
top = self.top = Toplevel(parent)
Label(top, text="Product EAN").pack() #pop-up box text
self.e = Entry(top, cursor = "xterm", width=25) #Input textbox
self.e.pack(padx=40)
b = Button(top, text="Submit", command=self.ok, cursor = "hand2") #Submit button for pop-up box
b.pack(pady=5)
....
root = Tk()
d = MyDialog(root)
root.wait_window(d.top)
That's all the code to do with textboxes - self.ok is the scraper so is unimportant to this issue. Could someone explain to me or help me fix the issue as I can't see why the following picture is the output from that.
Thank you in advance.
The problem is you are opening a Tk() window and then another, TopLevel() window on top of that, if all you want is one window, the you just use the Tk() window. (The problem is a little unclear, but this is what I assume you are asking).
To fix this you can just remove the TopLevel() window. Like so:
class MyDialog:
def __init__(self, parent): #Pop-up textbox
Label(parent, text="Product EAN").pack() #pop-up box text
self.e = Entry(parent, cursor = "xterm", width=25) #Input textbox
self.e.pack(padx=40)
b = Button(parent, text="Submit", command=self.ok, cursor = "hand2") #Submit button for pop-up box
b.pack(pady=5)
root = Tk()
d = MyDialog(root)
root.mainloop()
My code shows FunctionAllocation label and two radio buttons, and once one radio button is clicked, it shows Subject ID label and its entry bar. Once return key is clicked, all widgets are destroyed and new message appears.
Everything works smoothly if radio button is clicked once. However, if I click a radio button and then click another radio button, Subject ID label and its entry bar do not disappear despite .destroy() command.
How do I make sure the widgets disappear no matter which & how many times the radio buttons are pressed?
Thank you so much in advance!
from Tkinter import *
class Application(Frame):
#Initial Settings
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.radioButtons()
#Place Initial Buttons
def radioButtons(self):
#Variable to tie two radio buttons
self.tieVar1 = StringVar()
#Text before FA buttons
self.buttonLabel1 = Label(root, text="Function Allocation:")
self.buttonLabel1.place(relx=0.35, rely=0.3, anchor=CENTER)
#Two Radio FA buttons
self.radio1 = Radiobutton(text = "FA_F", variable=self.tieVar1, value="FA1", command=lambda: self.addSubject())
self.radio1.place(relx=0.5, rely=0.3, anchor=CENTER)
self.radio2 = Radiobutton(text = "FA_I", variable=self.tieVar1, value="FA2", command=lambda: self.addSubject())
self.radio2.place(relx=0.6, rely=0.3, anchor=CENTER)
def addSubject(self):
#Text before ID entry bar
self.buttonLabel2 = Label(root, text="Subject ID:")
self.buttonLabel2.place(relx=0.35, rely=0.6, anchor=CENTER)
#ID entry bar
self.myEntry = Entry()
self.myEntry.place(relx=0.5, rely=0.6, anchor=CENTER)
self.contents = StringVar()
self.contents.set("Sample Text")
self.myEntry["textvariable"] = self.contents
self.myEntry.bind('<Key-Return>', self.reset_contents)
#Action when return key pressed after typing subject ID
def reset_contents(self, event):
#Delete all
self.buttonLabel1.destroy()
self.buttonLabel2.destroy()
self.radio1.destroy()
self.radio2.destroy()
self.myEntry.destroy()
#Setting up new window
self.setActions()
def setActions(self):
Label(text="Done!", font=("Times", 10, "bold")).place(relx=0.5, rely=0.5, anchor=CENTER)
#Final settings to keep window open
root = Tk()
root.geometry("1000x400")
app = Application(master=root)
app.mainloop()
You are making a new Label and Entry every time you click that button. However your destroy only destroys the last one created. The easiest fix is to simply check if the Label has already been created:
def addSubject(self):
if hasattr(self, 'buttonLabel2'):
return # abort this method if the Label is already created
# rest of your method
Unrelated, but if you want your Radiobuttons to start in a blank state rather than a tristate, you need to initialize the StringVar like this:
self.tieVar1 = StringVar(value='Novel')
So I am trying to when the person clicks on the button I created, to display the text they wrote on the input field but for some reason when I click the button it displays:
.!entry
And I don't know what I am doing wrong since I am new to python so I wanted to know how to fix this problem, here's my code and thank you since any help is appreciated!
from tkinter import *
screen = Tk()
def print_input():
text2 = Label(screen, text=input_field)
text2.grid(row=1, columnspan=3)
text = Label(screen, text="Write to print:")
text.grid(row=0, column=0)
input_field = Entry(screen)
input_field.grid(row=0, column=1)
submit_button = Button(screen, text="Print!", fg="yellow", bg="purple",
command=print_input)
submit_button.grid(row=0, column=2)
screen.mainloop()
Change:
def print_input():
text2 = Label(screen, text=input_field)
to:
def print_input():
text2 = Label(screen, text=input_field.get())
# ^^^^^^
You're telling the text of the label to be set to the Entry widget instead of the Entry widget's content. To get the content of the Entry widget, use the .get() method.
The funky string you're seeing in the label is the tkinter name for the Entry widget.