I downloaded pycharm and I copied some code from a youtube tutorial into it which worked for the person making the video but when i tried running it it didnt work and this is what it said:
C:\Python27\python.exe C:/Python27/Lib/site-packages/wheel/test/test245425232.py
Traceback (most recent call last):
File "C:/Python27/Lib/site-packages/wheel/test/test245425232.py", line 9, in <module>
button1.bind("<button1>", printName)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1098, in bind
return self._bind(('bind', self._w), sequence, func, add)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1053, in _bind
self.tk.call(what + (sequence, cmd))
_tkinter.TclError: bad event type or keysym "button1"
Process finished with exit code 1
Here is the code:
from tkinter import *
root=Tk()
def printName():
print("hi stuff")
button1=Button(root, text="print my name")
button1.bind("<button1>", printName)
button1.pack()
root.mainloop()
It's better with :
button1.bind("<Button-1>", printName)
But you may want to plug your function directly to your button widget, a binding is not necessary here, it can be useful with a label widget for example :
button1=Button(root, text="print my name", command=printName)
("Button-1" is the name of the mouse left click event, not a widget variable name)
Otherwise you need to declare your function printName with a parameter : the event given by your binding.
def printName(event):
print("hi stuff")
button1=Button(root, text="print my name")
button1.bind("<Button-1>", printName)
Like i said, a binding like this could make sense with another widget :
from tkinter import *
root=Tk()
def printName(event):
print("hi stuff")
label1=Label(root, text="print my name")
label1.bind("<Button-1>", printName)
label1.pack()
root.mainloop()
Related
So today I tried to use python classes for the first time, to remove the excessive use of global keyword. I am trying to create a tkinter window in which, when we click one button it removes the clicked button and replaces it with a new button. And when we click it again, it removes this button and replaces the old (first) button and this should cycle through out...
This is my code which I made:
# ================= Importing Modules ===================
from tkinter import *
import tkinter as tk
# ====================================================
class Test():
# ============= Play Button Click =============
def fun1(self):
self.hi.destroy()
self.he.place(x=350,y=340)
# ============ Pause Button Click =============
def fun2(self):
self.he.destroy()
self.hi.place(x=350,y=340)
# ============ Player Window ================
def __init__(self):
self.root = Tk()
self.root.geometry('700x400')
self.root.resizable(0,0)
self.root["bg"] = "black"
self.hi = tk.Button(self.root, text="button 1", bg="white", bd=0, command=lambda: self.fun1() , relief=RIDGE)
self.hi.place(x=350,y=340)
self.he = tk.Button(self.root, text="button 2", bg="white", bd=0, command=lambda: self.fun2() , relief=RIDGE)
self.root.mainloop()
# ============== Calling ===========
if __name__ == '__main__':
Test()
But Instead of the desired output, sadly, I got this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "C:/XXX/XXX/Desktop/test.py", line 29, in <lambda>
self.he = tk.Button(self.root, text="button 2", bg="white", bd=0, command=lambda: self.fun2() , relief=RIDGE)
File "C:/XXX/XXX/Desktop/test.py", line 16, in fun2
self.hi.place(x=350,y=340)
File "C:\Program Files\Python310\lib\tkinter\__init__.py", line 2477, in place_configure
self.tk.call(
_tkinter.TclError: bad window path name ".!button"
SO MY QUESTION IS:
doubt1 = Any idea what I am doing wrong?
doubt2 = Or isn't this possible?
if doubt1 or doubt2:
Please explain it...
elif:
Please tell me a better alternative or idea, how to do this efficiently.
else:
Note: I have researched so many questions. Nothing helped me out. Especially ---|
↓
ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤthis one.
You're destroying self.hi and then later trying to call place on the destroyed button. Once a widget has been destroyed you can no longer use it.
If you want to keep cycling the buttons, don't destroy them. Since you are using place, you can use self.hi.place_forget() and self.he.place_forget() to remove the buttons from view without destroying them.
I am exploring GUI's at the moment. What I want is to have a GUI with a 2 buttons and I want each of the buttons to run a separate python script when clicked.
I have outlined my code below (the first button runs just fine but I am having issues with the second button.
Error Message when I choose the second button:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
Code:
from tkinter import *
import tkinter as tk
master = Tk()
def First_Scriptcallback():
exec(open(r'Desktop\Automation\First_Script.py').read())
def second_Scriptcallback():
exec(open(r'Desktop\Automation\Second_Script.py').read())
#master.title("Test GUI")
#canvas = tk.Canvas(master, height=300, width = 400)
#canvas.pack()
firstButton = Button(master, text="Run first script", command=First_Scriptcallback)
firstButton.pack()
secondButton = Button(master, text="Run second script", command=second_Scriptcallback)
secondButton.pack()
mainloop()
Thanks
As #matiiss suggested importing the other scripts into your program can help and it can be done like this,
import First_Script as first
import Second_Script as second
from tkinter import *
import tkinter as tk
master = Tk()
def First_Scriptcallback():
first.function_name()#here you must create functions in first_script to call in this main script
def second_Scriptcallback():
second.function_name()
#master.title("Test GUI")
#canvas = tk.Canvas(master, height=300, width = 400)
#canvas.pack()
firstButton = Button(master, text="Run first script", command=First_Scriptcallback)
#command=first.function_name
#we can also directly call an function using above command,but sometimes there are problems related to this approch
firstButton.pack()
secondButton = Button(master, text="Run second script", command=second_Scriptcallback)
#command=second.function_name
secondButton.pack()
mainloop()
here for this example the scripts and the program must be in same directory.
I am making an application that involves tkinter, and will eventually involve sockets. My code currently consists of this:
import tkinter as tk # imports tkinter module
from tkinter import * # imports tkinter module
a=tk.Tk()
a.title('Custodian Alert Tool')
List=['','','']
List.clear()
def Clear():
for widget in a.winfo_children(): # clears the window for the next Page
widget.destroy()
def Home():
Clear()
Label(a,text='Welcome to the Custodian Alert Tool.').pack()
Label(a,text='').pack()
SubmitButton=tk.Button(a,text='Submit A Ticket',command=Submit)
SubmitButton.pack()
ExitButton=tk.Button(a,text='Exit',command=Exit)
ExitButton.pack()
a.mainloop()
def Submit():
Clear()
def Append1(): # the button calls this function when pressed
List.append(x.get())
Gender()
Label(a,text='Which bathroom are you reporting for?').pack()
f=tk.Frame(a)
f.pack()
x=tk.StringVar()
E=tk.Entry(f,textvariable=x)
E.grid(row=1,column=1)
b1=tk.Button(f,text='Submit',command=Append1) # the error occurs after I click this button
b1.grid(row=1,column=2)
def Gender():
Clear()
def Append2(y):
List.append(y)
Issue()
Label(a,text='Boys or Girls?').pack()
f=tk.Frame(a)
f.pack()
b1=tk.Button(f,text='Boys',command=Append2('Boys'))
b1.grid(row=1,column=1)
b2=tk.Button(f,text='Girls',command=Append2('Girls'))
b2.grid(row=1,column=2)
def Issue():
Clear()
def Exit():
a.destroy()
Home()
When I click the b1 button under the Submit function, however, I get this:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 1550, in __call__
return self.func(*args)
File "/Users/skor8427/Desktop/AlertClient.py", line 27, in Append1
Gender()
File "/Users/skor8427/Desktop/AlertClient.py", line 45, in Gender
b1=tk.Button(f,text='Boys',command=Append2('Boys'))
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 2209, in __init__
Widget.__init__(self, master, 'button', cnf, kw)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 2139, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: bad window path name ".4610182280"
This is the biggest error I have ever gotten and I have no clue where to begin. Anyone know what I can do?
When you do this:
b1=tk.Button(f,text='Boys',command=Append2('Boys'))
It behaves exactly the same as this:
result = Append2('Boys'))
b1=tk.Button(f,text='Boys',command=result)
When Append2 is called, it calls Issue which calls Clear which destroys all of the children in a. f is in a so f gets destroyed. That means that you're trying to create b1 as a child of a widget that has been destroyed. And that is why you get the error "bad window path name" -- that cryptic string is the name of the widget that has been destroyed.
You need to modify the construction of b1 to be something like this:
b1 = Button(f, text='Boys', command=lambda: Append2('Boys'))`
That will defer the calling of Append2 until the button is clicked.
#AssessmentGUI
from Tkinter import *
window=Tk()
window.title('Troubleshooting')
def start():
wet()
def wet():
global wetlabel
wetlabel=Label(window, text="Has the phone got wet? Y/N")
wetsubmit()
def wetsubmit():
wetlabel.pack()
wetanswer=(entry.get())
if wetanswer=="Y":
print"ADD SOLUTION"
else:
dropped()
def dropped():
global droppedlabel
dropwindow.title('Troubleshooting')
dropwindow.mainloop()
droplabel=Label(dropwindow, text="Has the phone been dropped? Y/N")
droplabel.pack()
dropButton.pack()
dropsubmit()
def dropsubmit():
print "test"
window.geometry("300x100")
global wetsubmit
Button=Button(window, text="Submit Answer", activebackground="Green",command= wetsubmit , width=100)
dropwindow=Tk()
dropButton=Button(dropwindow, text="Submit Answer", activebackground="Green",command= dropsubmit , width=100)
entry=Entry(window, text="Test", width=100)
start()
entry.pack()
Button.pack()
window.mainloop()
Above is my code which isn't working due to the error. Basically what I want to happen is that each window opens another window after it for the next question on the troubleshooting program! If anyone has the task it would be nice if youy could suggest a better method if mine is unfixable.
The error message says:
Traceback (most recent call last):
File "H:\GCSE\Computing\GUI.py", line 36, in <module>
dropButton=Button(dropwindow, text="Submit Answer", activebackground="Green",command= dropsubmit , width=100)
AttributeError: Button instance has no __call__ method*
This is after a little bit of tweaking to the original code but I cannot fix this problem!
You have a class, named Button,and then you create a variable named Button. You have now destroyed the class, so the next time you try to create a button, you are calling your variable instead.
Lesson: don't use variable names that are the same as classes.
Hi I am using Python27 on Window7 OS, i am trying to create a Tk GUI with button, when the button is press a file directory will appear. But the following code won't do anything. Did i miss out something?
import webbrowser
import Tkinter as Tk
def action(self):
webbrowser.open ('C:\AgmPlots')
win = Tk.Toplevel()
frame = Tk.Frame(master=win).grid(row=1, column=1)
button = Tk.Button(master=frame, text='press', command= lambda: action())
You've got three big problems.
First, you never start the GUI. You need something like win.mainloop() at the end to actually do anything.
Second, your button isn't actually laid out within the frame, so you won't see it. You need something like button.pack().
Finally, your command is a function that calls action(), with no arguments. But you've defined it to require a parameter. So, all that will happen when you click it is that Tk will log a traceback that looks like this:
Exception in Tkinter callback
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1470, in __call__
return self.func(*args)
File "tkt.py", line 8, in <lambda>
button = Tk.Button(master=frame, text='press', command= lambda: action())
TypeError: action() takes exactly 1 argument (0 given)
To fix that, either don't add the unnecessary self parameter to action (this is a function, not a method), or explicitly pass some dummy to match it in your lambda.
While we're at it, lambda: action() does exactly the same thing as action itself, except more verbose, harder to read, and slower. You should never use unescaped backslashes in non-raw string literals. And we might as well remove the stray spaces and PEP8-ify everything to make it consistent.
So, putting it all together:
import webbrowser
import Tkinter as Tk
def action():
webbrowser.open(r'C:\AgmPlots')
win = Tk.Toplevel()
frame = Tk.Frame(master=win).grid(row=1, column=1)
button = Tk.Button(master=frame, text='press', command=action)
button.pack()
win.mainloop()