I get the error "NameError: global name 'entryWidget' is not defined" in the following piece of Python 3 tkinter code:
from tkinter import *
import tkinter
def displayText():
tkinter.messagebox.showinfo("Tkinter Entry Widget", "Text value =" + entryWidget)
class Application(Frame):
def createWidgets(self):
root.title("TITLE")
textFrame = Frame(root)
entryLabel = Label(textFrame)
entryLabel["text"] = "Enter the text:"
entryLabel.pack(side=LEFT)
entryWidget = Entry(textFrame)
entryWidget["width"] = 50
entryWidget.pack(side=LEFT)
textFrame.pack()
button = Button(root, text="Submit", command=displayText)
button.pack()
self.QUIT = Button(self)
self.QUIT["text"] = "QUIT"
self.QUIT["fg"] = "red"
self.QUIT["command"] = self.quit
self.QUIT.pack()
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.createWidgets()
root = Tk()
app = Application(master=root)
app.mainloop()
root.destroy()
The code itself is designed to create a text box (with text next to it), an enter button for the text box and a quit button. When text is entered in the text box and enter is pressed then a message box should appear telling the user what they entered. The quit button just quits the script.
How can I fix the error I am getting (I am aware what the error means, just don't know how to fix it in this scenario). Note that I am new to tkinter and GUI code.
What about something like that:
from tkinter import *
import tkinter
class Application(Frame):
def createWidgets(self):
root.title("TITLE")
textFrame = Frame(root)
entryLabel = Label(textFrame)
entryLabel["text"] = "Enter the text:"
entryLabel.pack(side=LEFT)
self.entryWidget = Entry(textFrame)
self.entryWidget["width"] = 50
self.entryWidget.pack(side=LEFT)
textFrame.pack()
button = Button(root, text="Submit", command=self.displayText)
button.pack()
self.QUIT = Button(self)
self.QUIT["text"] = "QUIT"
self.QUIT["fg"] = "red"
self.QUIT["command"] = self.quit
self.QUIT.pack()
def displayText(self):
tkinter.messagebox.showinfo("Tkinter Entry Widget", "Text value =" + self.entryWidget.get())
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.createWidgets()
root = Tk()
app = Application(master=root)
app.mainloop()
root.destroy()
I don't have tkinter here so I can't check it. But I hope it will help.
Move definition of displayText into the createWidgets method.
Related
I'm doing a little "Supplementshop" with python 3.7.2 and tkinter. I want to use a "go back to the main window"-button. Because I'm creating new windows through buttons and functions, I think I can't use the .destroy method... After one full day of testing some codes I still did not managed to get this button. I guess, I need now some help. :D
Because the code is about 600 lines already, I just did a short version from it. Hope it's enough. Code:
from tkinter import *
import sys, os
class MainWindow():
def __init__(self, master, title, size):
self.master = master
self.title = title
self.size = size
self.master.title(self.title)
self.master.geometry(self.size)
self.hitext = Label(self.master,
text="some random text,\n to change the previous text lol").pack(fill=X, pady=10)
self.productButton = Button(self.master,
text="second window",
width=15,
command=self.productButtonClicked).place(x=15, y=55)
self.quitMainWindow = Button(self.master,
text="exit",
width=15,
command=mainWindow.quit).place(x=170, y=55)
def productButtonClicked(self):
productWindow = Toplevel()
productFenster = ProductMenuWindow(productWindow, "second window", "260x100")
class ProductMenuWindow():
def __init__(self, master, title, size):
self.master = master
self.title = title
self.size = size
self.master.geometry(self.size)
self.master.title(self.title)
self.text = Label(self.master, text="what do you want to buy?").pack(fill=X, pady=10)
self.gobackButton = Button(self.master,
text="go back to main window",
width=20,
command="").place(x=55, y=50) #here should be the command for the button
if __name__ == "__main__":
mainWindow = Tk()
mainFenster = MainWindow(mainWindow, "root/main/first window", "300x95")
mainWindow.mainloop()
If I put command=mainWindow.quit the mainwindow of course gets destroyed and the programm stops. So heres the point, I dont now further because .destroy is not working here... Also sorry for some english mistakes :P
I've made some changes.
Compare my version with yours.
from tkinter import *
import sys, os
class MainWindow():
def __init__(self, master, title, size):
self.master = master
self.title = title
self.size = size
self.master.title(self.title)
self.master.geometry(self.size)
self.hitext = Label(self.master,
text="some random text,\n to change the previous text lol").pack(fill=X, pady=10)
self.productButton = Button(self.master,
text="second window",
width=15,
command=self.productButtonClicked).place(x=15, y=55)
self.quitMainWindow = Button(self.master,
text="exit",
width=15,
command=self.on_cancel).place(x=170, y=55)
def productButtonClicked(self):
#productWindow = Toplevel()
obj = ProductMenuWindow(self, "second window", "260x100")
#productFenster = ProductMenuWindow(productWindow,)
def on_cancel(self):
self.master.destroy()
class ProductMenuWindow(Toplevel):
def __init__(self, parent, title, size):
super().__init__(name='product_main_menu')
self.parent = parent
self.title(title)
self.size = size
self.geometry(size)
self.text = Label(self, text="what do you want to buy?").pack(fill=X, pady=10)
self.gobackButton = Button(self,
text="go back to main window",
width=20,
command=self.on_cancel).place(x=55, y=50) #here should be the command for the button
def on_cancel(self):
self.destroy()
if __name__ == "__main__":
mainWindow = Tk()
mainFenster = MainWindow(mainWindow, "root/main/first window", "300x95")
mainWindow.mainloop()
p.s.
super().__init__(name='product_main_menu')
It's used to have singleton on your ProductMenuWindow.
If you write super().__init__() you see that you could open more then one window.
I'm using Python 3.6.0 and I want to save the value of my combobox only when I hit my "Confirm Results" button. I have done a fair bit of searching - but maybe I have the wrong terminology - and I can't find the way to do this.
I am assuming the issues is with my line self.firstfaction_ent.bind("Button-1", self.firstfaction_onEnter). I am fairly confident that "Button-1" is not correct - however I have been trying everything.
from tkinter import *
from tkinter import ttk
class Application(Frame):
def __init__(self, master):
# Initialise the Frame
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
#Define Combobox for Faction
self.firstfaction_ent=ttk.Combobox(self,textvariable=varSymbol, state='readonly')
self.firstfaction_ent.bind("<Button-1>", self.firstfaction_onEnter)
self.firstfaction_ent['values']=Faction
self.firstfaction_ent.grid(row=2, column=1)
#create a submit button
self.enter_bttn = Button(self,text = "Confirm Your Results", command = self.firstfaction_onEnter).grid(row=7, column=1)
def firstfaction_onEnter(self, event):
Faction_First = varSymbol.get()
print(Faction_First)
#main
root = Tk()
#Window Title & size
root.title("Sports Carnival Entry Window")
root.geometry("600x500")
varSymbol=StringVar(root, value='')
varSecondFaction=StringVar(root, value='')
Faction = ["Blue", "Green", "Yellow", "Red"]
#create a frame in the window
app = Application(root)
root.mainloop( )
You need the confirm_button to capture the selection in the combo box; there is no need to bind the combo box selection to the capture; you also do not need to pass an event to firstfaction_onEnter; you can directly use the combo_box to obtain the value of the selection.
from tkinter import *
from tkinter import ttk
class Application(Frame):
def __init__(self, master):
# Initialise the Frame
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
#Define Combobox for Faction
self.firstfaction_ent = ttk.Combobox(self, textvariable=varSymbol, state='readonly')
# self.firstfaction_ent.bind("<Button-1>", self.firstfaction_onEnter)
self.firstfaction_ent['values'] = Faction
self.firstfaction_ent.grid(row=2, column=1)
#create a submit button
self.enter_bttn = Button(self, text="Confirm Your Results", command=self.firstfaction_onEnter).grid(row=7, column=1)
def firstfaction_onEnter(self):
Faction_First = self.firstfaction_ent.get()
print(Faction_First)
#main
root = Tk()
#Window Title & size
root.title("Sports Carnival Entry Window")
root.geometry("600x500")
varSymbol=StringVar(root, value='')
varSecondFaction=StringVar(root, value='')
Faction = ["Blue", "Green", "Yellow", "Red"]
#create a frame in the window
app = Application(root)
root.mainloop( )
NameError: name 'onOpen' is not defined
There is something wrong with the command function. I am not sure what I did wrong here. I had the code tested before the onOpen function and it works fine.
import tkinter as tk
from tkinter import filedialog
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.pack()
self.createWidgets()
def onOpen():
""" Ask the user to choose a file and update the values of label change button"""
button_label.set(filedialog.askopenfilename(filetypes = ()))
def createWidgets(self):
#instruction label
self.labelInstruct = tk.Label(self, text="Instructions:", padx=10, pady=10)
self.labelInstruct = tk.Label(self, text="All you have to do is insert the file and save it.\n The conversion is instant", padx=10, pady=10)
self.labelInstruct.pack()
#insertfile button
self.ifbut = tk.Button(self, text="Insert File", command=onOpen)
self.ifbut.pack()
button_label = tk.StringVar(self)
text = tk.Label(self, textvariable = button_label)
text.pack()
#save button
self.saveLabel = tk.Label(self, text="Save File", padx=10, pady=10)
self.saveLabel.pack()
self.saveButton = tk.Button(self)
self.saveButton.pack()
#quit button
self.quitButton = tk.Button(self, text='Quit',
command=self.quit)
self.quitButton.pack()
app = Application()
app.master.title('Sample application')
app.mainloop()
Seeing that there are many problems with the way this code is written I am only going to point out a few of them and tackle the main question from the OP.
Lets start with the fact that you need to define the main window with something like root = tk.Tk() and you also need to make sure all your methods in your class have the argument self as the first argument.
Also any variable you are defining also should have self so that the class can interact with it. This (button_label) for example should be self.button_label.
There is no reason to use return the way you are trying to in the onOpen(self): method. Return does not work like that. Return is there so you can return a value to something that is calling the function/method to be used for something else and is not for setting the value of something.
Note that I also add the root window variable to the app = Application(root) line. This lets us pass the main window into the class.
all and all the following should work for the onOpen(self): function but the rest still needs some work.
import tkinter as tk
from tkinter import filedialog
class Application(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.pack()
self.createWidgets()
def onOpen(self):
""" Ask the user to choose a file and update the values of label change button"""
self.button_label.set(filedialog.askopenfilename(filetypes = ()))
def createWidgets(self):
#instruction label
self.labelInstruct = tk.Label(self.parent, text="Instructions:", padx=10, pady=10)
self.labelInstruct = tk.Label(self.parent, text="All you have to do is insert the file and save it.\n The conversion is instant", padx=10, pady=10)
self.labelInstruct.pack()
#insert file button
self.ifbut = tk.Button(self.parent, text="Insert File", command = self.onOpen)
self.ifbut.pack()
self.button_label = tk.StringVar()
self.text = tk.Label(self.parent, textvariable = self.button_label)
self.text.pack()
#save button
self.saveLabel = tk.Label(self.parent, text="Save File", padx=10, pady=10)
self.saveLabel.pack()
self.saveButton = tk.Button(self.parent, text = "Save")
self.saveButton.pack()
#quit button
self.quitButton = tk.Button(self.parent, text='Quit', command=self.quit)
self.quitButton.pack()
root = tk.Tk()
app = Application(root)
app.master.title('Sample application')
app.mainloop()
You need to return the function value as below:
def onOpen():
""" Ask the user to choose a file and update the values of label change button"""
return button_label.set(filedialog.askopenfilename(filetypes = ()))
I create a StringVar, slave it to a label, change the value of the StringVar, and the label does not update.
class DlgConnection:
def start(self)
self.dlgConnection = Tk()
self.dlgConnection.title("Connection")
self.dlgConnection.geometry("380x400")
self.dlgConnection.resizable(width=False,height=False)
self.statusText = StringVar()
self.lStatusText = Label(self.dlgConnection, width=80, anchor="w", textvariable=self.statusText)
self.lStatusText.place(x = 0, y = 360, width=380, height=25)
self.setStatus("Welcome 2")
def setStatus(self, status_text):
print(status_text) #the print is just to show me I changed the text
self.statusText.set(status_text)
self.lStatusText.update() # I tried this out of desperation
I rewrote your code to something that works. The window opens with the text "Initial" and then once a second switches between "Welcome 1" and "Welcome 2".
from tkinter import *
from time import sleep
class DlgConnection(Frame):
def __init__(self, master):
Frame.__init__(self, master)
master.title("Connection")
master.geometry("380x400")
master.resizable(width=False,height=False)
self.statusText = StringVar()
self.statusText.set('Initial')
self.lStatusText = Label(master, width=80, anchor="w", textvariable=self.statusText)
self.lStatusText.place(x = 0, y = 360, width=380, height=25)
self.pack()
def setStatus(self, status_text):
print(status_text) #the print is just to show me I changed the text
self.statusText.set(status_text)
self.update_idletasks()
root = Tk()
dlgConnection = DlgConnection(root)
dlgConnection.update()
for i in range(6):
sleep(1) # Need this to slow the changes down
dlgConnection.setStatus('Welcome 2' if i%2 else 'Welcome 1')
This question is very similar to Update Tkinter Label from variable
I'm trying to add a "Done" button to my program that will print the content of both Entry widgets to a new box. I can get the button to appear, but I can't get the information to show up in a new box. What am I doing wrong?
from Tkinter import *
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.grid()
self._name = StringVar()
self._name.set("Enter name here")
self._age = IntVar()
self._age.set("Enter age here")
top = self.winfo_toplevel() # find top-level window
top.title("Entry Example")
self._createWidgets()
self._button = Button(self,
text = "Done")
self._button.grid(row = 1, column = 0, columnspan = 2)
def _createWidgets(self):
textEntry = Entry(self, takefocus=1,
textvariable = self._name, width = 40)
textEntry.grid(row=0, sticky=E+W)
ageEntry = Entry(self, takefocus=1,
textvariable = self._age, width = 20)
ageEntry.grid(row=1, sticky=W)
def _widget(self):
tkMessageBox.showinfo
# end class Application
def main():
Application().mainloop()
You need to assign an action to your button using command: option.
To get what is written in Entry you need to use get() method.
showinfo you need two arguments, one is the title, the other one is what is going to be shown.
Also you need to import tkMessageBox.
Here is a working example.
import Tkinter as tk
import tkMessageBox
class Example(tk.Frame):
def __init__(self,root):
tk.Frame.__init__(self, root)
self.txt = tk.Entry(root)
self.age = tk.Entry(root)
self.btn = tk.Button(root, text="Done", command=self.message)
self.txt.pack()
self.age.pack()
self.btn.pack()
def message(self):
ent1 = self.txt.get()
ent2 = self.age.get()
tkMessageBox.showinfo("Title","Name: %s \nAge: %s" %(ent1,ent2))
if __name__=="__main__":
root = tk.Tk()
root.title("Example")
example = Example(root)
example.mainloop()