Error button is not defined? - python

This is my code:
import sys
from tkinter import *
def next_screen(names):
for widget in names:
widget.place_forget()
def forget_page1():
widgets = [mLabel1, button]
next_screen(widgets)
mGui = Tk ()
mGui.geometry("600x600+545+170")
mGui.title("MyMathDictionary")
mLabel1 = Label (text = "Welcome to MyMathDictionary. Press Next to continue.",
fg = "blue",bg = "white")
mLabel1.place (x= 150,y = 200)
button = Button (text = "Next", command = forget_page1 ())
button.place(x = 275,y = 230)
mGui.mainloop()
It tells me :
Traceback (most recent call last): File
"C:\Python33\Projects\MyMathDictionary.py", line 24, in <module>
button = Button (text = "Next", command = forget_page1 (mLabel,button)) NameError: name 'button' is not defined
What does this error message mean?

Change this line of code:
button = Button (text = "Next", command = forget_page1 ())
To this:
button = Button (text = "Next", command = forget_page1)
Your problem was that you were calling forget_page1 before the window loaded.
Also, as the comments have already said, your error is different than your code. But, I'll go over that quickly too just in case. If you want to send arguments to a button's command function, you need to use a lambda:
button = Button(command = lambda: func(arg1, arg2))

Related

Trying to get Tkinter button to add brackets on either side of button text with every press

I'm trying to create a button which has the same effect as the button from the version test from tkinter when using the command
py -m tkinter
in CMD. The button is supposed to display the text "Button", then with every press a set of brackets will be added on either side of the word. So on the first press, the text will read "[Button]", then the second press "[[Button]]", and so on.
Here is what I have:
from tkinter import *
from tkinter import ttk
def changeText():
textName = "[" + textName + "]"
root = Tk()
root.geometry('400x150')
root.title('Hit the button')
textName = "button"
frame = ttk.Frame(root, padding = 10).grid()
btn = ttk.Button(frame, text = textName, command = changeText).grid(column = 0, row = 0)
root.mainloop()
When I run my code, the window and button pops up correctly, however when the button is pressed, I get the error:
"X:\Pycharm Environments\venv\Scripts\python.exe" "X:/Pycharm Environments/Learning/tkinterPractie.py"
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\jared\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1885, in __call__
return self.func(*args)
File "X:\Pycharm Environments\Learning\tkinterPractie.py", line 5, in changeText
textName = "[" + textName + "]"
UnboundLocalError: local variable 'textName' referenced before assignment
I'm not really sure what I'm doing wrong here. Thanks for any help!
When you call .grid() on your button, the return value is None, so you have already lost the direct reference to your button. There are other ways of accessing it, but it would be much easier to just create the button and then put it in the layout in 2 steps. Also you need to set the button['text'] when changing the text. textName is just a variable holding a string and updating it only updates the value of the variable.
from tkinter import *
from tkinter import ttk
def changeText():
btn['text'] = "[" + btn['text'] + "]" # change to changing the buttons text
root = Tk()
root.geometry('400x150')
root.title('Hit the button')
textName = "button"
frame = ttk.Frame(root, padding = 10).grid()
btn = ttk.Button(frame, text = textName, command = changeText) # return the instance
btn.grid(column = 0, row = 0) # then input into the layout
root.mainloop()

Python Tkinter Listing options not showing info

I have a very basic question, i.e. by using Python Tkinter window I want to show list box and from that list, I want to show some information which I select. But I am getting some error.
import Tkinter
from Tkinter import*
import tkMessageBox
window = Tk()
window.title('ex - 4,listing option')
frame = Frame(window)
listbox = Listbox(frame)
listbox.insert(1, 'Manual')
listbox.insert(2, 'Auto')
listbox.insert(3, 'AI')
def dialog():
tkMessageBox('selection','your chice:' + \
listbox.get(listbox.curselection()))
btn = Button(frame, text = 'Choose',command = dialog)
btn.pack(side = RIGHT, padx = 5)
listbox.pack(side = LEFT)
frame.pack(padx = 30, pady = 30)
window.mainloop()
The error is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:\Users\Subhro Jyoti\Desktop\python\ex - 4,listing option", line 12, in dialog
tkMessageBox('selection','your chice:' + listbox.get(listbox.curselection()))
TypeError: 'module' object is not callable
tkMessageBox is a collection of different types of message boxes, you have to indicate which one you want to use. For example:
def dialog():
tkMessageBox.showinfo('selection','your chice:' +
listbox.get(listbox.curselection()))
Your choices are showinfo, showwarning, showerror, askquestion, askokcancel, askyesno, or askretrycancel

Changing Button text dynamically in Python

Could someone please explain to me why the following code does not work?
This is still an empty shell of a program and all I'm trying to do for now
is that when I click the connect button it changes the text to disconnect.
I would also like to change the command, but I'm sure if I'm able to change
the text I should be able to change the command as well.
Whenever I click the button it gives the following error
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\tkinter\__init__.py", line 1533, in __call__
return self.func(*args)
File "C:/Users/Rudolf/Desktop/test.py", line 5, in Connect
if btnConnect["text"] == "Connect":
TypeError: 'NoneType' object is not subscriptable
I don't understand. it seems so simple and logical. Please help.
Code in question:
from tkinter import *
def Connect():
"""Clicking the connect button"""
if btnConnect["text"] == "Connect":
btnConnect["text"] = "Disconnect"
else:
btnConnect["text"] = "Connect"
#Part in question^^
mGui = Tk()
mGui.geometry('500x420+1000+200')
mGui.title('PythonGUI')
#Variables:
cmdText = StringVar()
####################
#Heading
lblHead = Label(mGui, text='Distance Meassurement Device', font=("Helvetica", 18, "underline")).place(x=75,y=10)
#Connect Button and Label
btnConnect = Button(mGui, text = "Connect", command = Connect).place(x=20,y=70)
lblConnect = Label(mGui, text = 'Currently disconnected').place(x=20,y=100)
#Baud rate & COM port Labels
lblBaud = Label(mGui, text = 'Baud Rate : x').place(x=350,y=70)
lblCom = Label(mGui, text = 'COM port : x').place(x=350,y=90)
#Calibrate Buttons
btnCal0 = Button(mGui, text = 'Calibrate 0').place(x=20,y=200)
btnCal1 = Button(mGui, text = 'Calibrate 1').place(x=20,y=240)
#Stream Button
btnStream = Button(mGui, text = 'Stream on/off').place(x=20,y=350)
#Measurements block
lblMeasHead = Label(mGui, text = "Measurements:", font=("Helvetica", 12, "underline")).place(x=320,y=160)
lblDistanceHead = Label(mGui, text = "Distance:").place(x=320,y=190)
lblDistanceVal = Label(mGui, text = " x cm").place(x=380,y=190)
lblVelocityHead = Label(mGui, text = "Velocity:").place(x=320,y=210)
lblVelocityVal = Label(mGui, text = " x m/s").place(x=380,y=210)
#Send command block
lblCmd = Label(mGui, text = "Enter Command").place(x=330,y=295)
edtCmd = Entry(mGui,textvariable=cmdText).place(x=320,y=320)
btnSendCmd = Button(mGui, text = 'Send Command').place(x=330,y=345)
mGui.mainloop()
The issue is that you are creating btnConnect as -
btnConnect = Button(mGui, text = "Connect", command = Connect).place(x=20,y=70)
.place() method does not return back the created Button object (it was actually returned by Button() ), it does not return back anything, so you get None in btnConnect , and this causes the issue you are getting. You should move the .place() to the next line. Example -
btnConnect = Button(mGui, text = "Connect", command = Connect)
btnConnect.place(x=20,y=70)
So that btnConnect correctly points to the created Button object.
You are currently creating all widgets like above(calling .place() immediately) , so you would encounter same issue if you try to access those widgets again later on. And most probably you would need to make similar changes to all widgets that you want to be able to access later on.

2nd Page not showing up?

This is my code :
import sys
from tkinter import *
#first new screen
def next_screen(names):
for widget in names:
widget.place_forget()
buttonhyp = Button (text = "button1",fg = "blue",command = hypoténusegetdef())
buttonhyp.grid (row = 1,column = 2)
def forget_page1():
widgets = [mLabel1, button]
next_screen(widgets)
################################################################################
def hypténusegetdef ():
widgets1 = [buttonhyp]
nextscreen1(widgets1)
def next_screen(names):
for widget in names:
widget.place_forget()
hyplabel1 = Label (text = "This is my text")
#first page things
mGui = Tk ()
mGui.geometry("600x600+545+170")
mGui.title("MyMathDictionary")
mLabel1 = Label (text = "Welcome to MyMathDictionary. Press Next to continue.",
fg = "blue",bg = "white")
mLabel1.place (x= 150,y = 200)
button = Button (text = "Next", command = forget_page1 )
button.place(x = 275,y = 230)
mGui.mainloop()
What i'm trying to do is to open the program and get the user to click on "Next" and then to show another button which is called "button1" and when the user clicks on "button1" it shows up a text called which says "This is my text" in my code.But when i run it i click on "Next" and nothing shows up i checked and re- checked but nothing seems to work.Any help would be appreciated.
#
I am not an expert, but i will give it a try.
Firstly, import sys is not necessary. And importing all the objects from tkinter module using from tkinter import* is not recommended. You should use import tkinter or import tkinter as tk to avoid unexepcted consequences.
You have 2 functions with the same name. next_screen(names) which should not happen.
Instead of using widgets = [mLabel1, button] to hide the widgets, you should put them in a frame so that you can use winfo_children() to find all the children widgets.
You should put the parent widget name when you create buttons and labels. for example,
import tkinter as tk
root = tk.Tk()
mylabel = tk.Label(root,text='this is a label')
mylabel.pack()
root.mainloop()
In your first next_screen(names) function , you used grid method to display the button. You should not mix the grid method and place method.
This is something i came up with
import tkinter as tk
def Screen_1():
Clear(myframe)
mybutton2= tk.Button(myframe,text = "Button1", command = Screen_2)
mybutton2.pack()
def Screen_2():
Clear(myframe)
mylabel2= tk.Label(myframe,text = "This is my text",fg = "blue",bg = "white")
mylabel2.pack(side='top')
def Clear(parent):
for widget in parent.winfo_children():
widget.pack_forget()
root =tk.Tk()
myframe=tk.Frame(root)
myframe.pack()
mylabel1= tk.Label(myframe,text = "Welcome to MyMathDictionary. Press Next to continue.",fg = "blue",bg = "white")
mylabel1.pack(side='top')
mybutton1= tk.Button(myframe,text = "Next", command = Screen_1)
mybutton1.pack(side='bottom')
root.mainloop()
hope it helps!

button1 is not defined?

This is my code :
import sys
from tkinter import *
#first new screen
def hypoténusegetdef ():
widgets1 = button1
nextscreen1(widgets1)
def next_screen1(names):
for widget in names:
widget.place_forget()
hyplabel1 = Label (text = "This is my text")
def next_screen(names):
for widget in names:
widget.place_forget()
button1 = Button (text = "Button1",fg = "blue",command = hypoténusegetdef)
button1.grid (row = 1,column = 2)
def forget_page1():
widgets = [mLabel1, button]
next_screen(widgets)
################################################################################
#first page things
mGui = Tk ()
mGui.geometry("600x600+545+170")
mGui.title("MyMathDictionary")
mLabel1 = Label (text = "Welcome to MyMathDictionary. Press Next to continue.",
fg = "blue",bg = "white")
mLabel1.place (x= 150,y = 200)
button = Button (text = "Next", command = forget_page1 )
button.place(x = 275,y = 230)
mGui.mainloop()
I want the user to click on "next" and then a button appears caled "button1" after clicking on that button a text should appear "this is my text" but it gives me an error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
return self.func(*args)
File "C:\Python33\Projects\MyMathDictionary.py", line 7, in hypoténusegetdef
widgets1 = button1
NameError: global name 'button1' is not defined
Any help would be apreciated :
button1 is defined in next_screen, but used in hypoténusegetdef -- you can't use a variable from one function inside another. Looking at the rest of the code, the simplest thing would probably be to use a global variable that can be accessed anywhere (generally bad practice, but for short scripts they can make things easier)

Categories

Resources