I am making this small program, where the user can input the x and y axis of the screen where they wish to move the mouse to, and how many time they would like to click on that pixel.
My problem is when I try to put the variables into this function, the arguments apparently cannot be converted? The SetCurPos() is the problem, it will take SetCurPos(x,y), but I receive the error:
File "C:\Python27\Scripts\ManipulationTools.py", line 13, in click
SetCursorPos(x,y)
ArgumentError: argument 1: : Don't know how to convert parameter 1
My Code:
from Tkinter import *
import time
import ctypes
#from MoveCursor import click
class ManipulationTools():
##############FUNCTIONS###################################
def click(x,y, numclicks):
SetCursorPos = ctypes.windll.user32.SetCursorPos
mouse_event = ctypes.windll.user32.mouse_event
SetCursorPos(x,y)
E1.DELETE(0, END)
E2.DELETE(0, END)
E3.DELETE(0, END)
for i in xrange(numclicks):
mouse_event(2,0,0,0,0)
mouse_event(4,0,0,0,0)
#############END FUNCTIONS################################
root = Tk()
root.maxsize(width=400, height=400)
root.minsize(width=400, height=400)
root.config(bg="black")
L1 = Label(root,text="Enter the x and y value here:", fg="white", bg="black")
L1.place(x=20, y=20)
Lx = Label(root, text="X:",fg="white",bg="black")
Lx.place(x=170,y=20)
Ly = Label(root, text="Y:",fg="white",bg="black")
Ly.place(x=240,y=20)
Lnum = Label(root, text="Number of Times:",fg="white",bg="black")
Lnum.place(x=150, y=100)
E1 = Entry(root, width=5, bg="grey", )
E1.place(x=190,y=20)
E2 = Entry(root, width=5, bg="grey",)
E2.place(x=260,y=20)
E3 = Entry(root, width=5, bg="grey",)
E3.place(x=260,y=100)
a=IntVar(E1.get())
b=IntVar(E2.get())
c=IntVar(E3.get())
con = Button(root, command=click(a,b,c), text="Confirm", bg="white")
con.place(x=300,y=300)
root.mainloop()
My Traceback error when I click the button to confirm the numbers in the fields entered:
Traceback (most recent call last):
File "C:\Python27\Scripts\ManipulationTools.py", line 6, in
class ManipulationTools():
File "C:\Python27\Scripts\ManipulationTools.py", line 53, in ManipulationTools
con = Button(root, command=click(a,b,c), text="Confirm", bg="white")
File "C:\Python27\Scripts\ManipulationTools.py", line 13, in click
SetCursorPos(x,y)
ArgumentError: argument 1: : Don't know how to convert parameter 1
What you call ####functions#### are actually methods, and hence, the first argument they get is always the reference to the instance of their containing class, which commonly is named self. You can, however, name that parameter like you want to, which is what happened here:
class ManipulationTools():
def click(x,y, numclicks):
x is what elsewhere would be called self, not the first argument that you give when doing something like
tools = ManipulationTools()
tools.click(100,200,1) ## this should actually give you an error -- ManipulationTools.click gets called with 4 arguments (self, 100, 200, 1), but is only defined for 3 (self, y, numclicks)
The right thing to do is:
class ManipulationTools():
def click(self, x,y, numclicks):
Related
I am trying to create a pop up window with Tkinter where I can enter values with an entry window to use them in the main code.
Currently I am trying to simply output the input. I can't get it to work, does anyone have an idea how I can solve this problem?
Here is a small snippet of my code. I have not used the variables from the functions anywhere else in the code.
root = Tk() # set up GUI
menuleiste = Menu(root) #menu bar
def take_over_Temp():
#Tempstring = str(eKnopf.get())
print(eKnopf.get())
print("got it")
def open_popup():
#global eKnopf
top= Toplevel(root)
top.geometry("750x250")
top.title("Child Window")
#Label(top, text= "Hello World!", font=('Mistral 18 bold')).place(x=150,y=80)
eKnopf = Entry(top, bd = 5).place(x=10,y=100, width=100)
button_take_Temp = Button(top, text='Set Temperature', fg="red", command=take_over_Temp)
button_take_Temp.place(x=10, y=150, width=100)
return(eKnopf)
optionen_menu.add_command(label="Offset", command = open_popup)
When I try it like this I get this Error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.9/tkinter/__init__.py", line 1892, in __call__
return self.func(*args)
File "/home/user/FAC.py", line 724, in take_over_Temp
print(eKnopf.get())
NameError: name 'eKnopf' is not defined
You need to pass in eKnopf as a parameter to take_over_Temp()
eKnopf = Entry(top, bd = 5)
eKnopf.place(x=10, y=100, width=100)
button_take_Temp = Button(
top,
text='Set Temperature',
fg="red",
# use a lambda to pass `eKnopf` as an argument
command=lambda ent=eKnopf: take_over_Temp(ent)
)
Then modify take_over_Temp to accept and use that value:
def take_over_Temp(ent):
print(ent.get())
FYI, the error you're seeing is essentially saying that the function take_over_Temp doesn't know what eKnopf is because it doesn't exist within the scope of the function.
I'm getting the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/Users/XXXXXXXXXXXXX/Desktop/Python/Test Py/TestGUI.py", line 37, in trans1
print(enter_principal)
NameError: name 'enter_principal' is not defined
I'm currently trying to learn python, so I'd be lying if I said I had any idea on what is going wrong. Here is my source code, trying to make a basic compound interest calculator. Getting this error when I'm trying to get an input from the user. Code:
#Importing GUI Module
import tkinter as tk
from tkinter import *
#Creating window
root = tk.Tk()
####Functions#####
#Root screen exit button
def exitroot():
root.destroy()
#principal input
def principal():
#Creating principal window and destroying home window
window = tk.Tk()
exitroot()
#Creating widgets
title_principal = tk.Label(window, text='Please enter your pricipal value: ')
enter_principal = tk.Entry(window)
b1 = tk.Button(window, text='Submit', command=trans1)
title_principal.grid()
enter_principal.grid()
b1.grid()
def trans1():
#temp function for testing purposes
print(enter_principal)
####
#CREATING HOME WINDOW WIDGETS
title_main = tk.Label(root, text="Compound Intrest Calculator", font=("Arial", 20, 'bold'))
start_button = tk.Button(root, text="Start", width='6', height='2', command=principal)
exit_button = tk.Button(root, text="Exit", width='6', height='2', command=exitroot)
credits_main = tk.Label(root, text="M.CXXXXXXXX 2020", font=("Arial", 8))
#PACKING HOME WINDOW WIDGETS VIA GRID
title_main.grid(row='0', columnspan='2')
start_button.grid(row='1', column='0')
exit_button.grid(row='1', column='1')
credits_main.grid(row='2', columnspan='2')
root.mainloop()
Any help is greatly appreciated! I apologise if my code is hard to follow or has blantant errors. I've spent some time looking for a fix but I am really struggling as none have worked.
You need to change
b1 = tk.Button(window, text='Submit', command=trans1)
TO:
b1 = tk.Button(window, text='Submit', command=lambda: trans1(enter_principal.get()))
The reason being is because you need to pass in the value typed into the tk.Entry by using enter_principal.get().
Lambda allows the function to be called only when the button is pressed.(since the command contains parenthesis and so would be called automatically)
Once you've passed this in, you can then pass it into the trans1 function and print it.
def trans1(answer):
# temp function for testing purposes
print(answer)
I'm very new to the tkinter module and have little to no experience with it.
I want to make a program where I could run it and an entry box would display as well as a button.
What I want the program to do is, when I left click the button, the canvas would close, and I would be able to assign a variable to the entry I typed in and be able to pass that to other functions. So I'd have tkinter.Entry('Type in text'), then after that I would click the tkinter.Button('Click Me'), and once I click the button the canvas would close and then be able to assign the tkinter.Entry as a variable that I could pass through to other functions.
In my program I was able to just do regular python without the canvas and type in an input() and then return that to my other functions, but I'm completely lost on how to remove the input() from console and replace it with a UI canvas with tkinter. Sorry if this isn't making a lot of sense.
import tkinter
window = tkinter.Tk()
window.title("Code Violation")
def Canvas():
keyword = tkinter.Label(window, text="Enter Keyword").grid(row=0)
tester = tkinter.Button(window, text="Generate File").grid(columnspan=2)
tkinter.Entry(window).grid(row=0, column=1)
window.mainloop()
----Afterwards Error Codes
Traceback (most recent call last):
File "C:/Users/oalbz/PycharmProjects/Code_Violation/CodeViolation.py", line 98, in <module>
main()
File "C:/Users/oalbz/PycharmProjects/Code_Violation/CodeViolation.py", line 29, in main
keyword = Canvas()
File "C:/Users/oalbz/PycharmProjects/Code_Violation/CodeViolation.py", line 12, in Canvas
Var = tkinter.StringVar()
File "C:\Users\oalbz\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 480, in __init__
Variable.__init__(self, master, value, name)
File "C:\Users\oalbz\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 317, in __init__
self._root = master._root()
AttributeError: 'NoneType' object has no attribute '_root'
I want to be able to take the entry.get() that's insie the callback function and return it to my main and use that as a parameter in my vacancy function
here is the code for my main
def main():
#Canvas()
keyword = Canvas()
print(keyword)
initial_index = open('CodeViolationIndex.html','r')
table_dict = removeTags(initial_index,'tr','td')
site_final_html = open('test.html','w')
#keyword = input('Enter Keyword you would like to search:')
vacancy(table_dict,keyword)
This is what I have so far in my Canvas function you gave me
def Canvas():
Var = tkinter.StringVar()
tkinter.Label(window, text="Enter Keyword").grid(row=0)
entry = tkinter.Entry(window, text="Enter Keyword",textvariable = Var)
entry.grid(row=1)
def callback():
keyword = entry.get()
#print(keyword)
window.destroy()
return keyword
tester = tkinter.Button(window, text="Generate File",command=callback)
tester.grid(columnspan=2)
keyword = callback()
return keyword
Try this code:
import tkinter
window = tkinter.Tk()
window.title("Code Violation")
def Canvas():
Var = tkinter.StringVar() #Making a variable which will store data
tkinter.Label(window, text="Enter Keyword:").grid(row=0) #Making label, no need to store it in a variable
entry = tkinter.Entry(window, text="Enter Keyword", textvariable = Var) #making entry
entry.grid(row=1)
def callback(): #this function will be triggered on button press
print(entry.get()) #get() method will give the value of the entry
window.destroy() #It will destroy the tkinter window
tester = tkinter.Button(window, text="Generate File", command = callback)
tester.grid(columnspan=2)
Canvas()
window.mainloop()
Edit:
Here is the code updated according to your updates:
import tkinter
def Canvas():
global keyword
window = tkinter.Tk()
window.title("Code Violation")
Var = tkinter.StringVar()
tkinter.Label(window, text="Enter Keyword").grid(row=0)
entry = tkinter.Entry(window, text="Enter Keyword",textvariable = Var)
entry.grid(row=1)
def callback():
global keyword
keyword = entry.get()
window.destroy() #This also quits the mainloop so function will continue to return statement
tester = tkinter.Button(window, text="Generate File",command=callback)
# >>>> >>>> >>>> ^ We are assigning the function callback here
tester.grid(columnspan=2)
window.mainloop()
return keyword
def main():
#Canvas()
keyword = Canvas()
print(keyword)
#...
main()
I am making a pop up window ,on press of a button on main window. The pop up window have many check buttons, I need to get the state of the check buttons back to main window and also to make use of a select all and deselect all button. But I am getting error using the variables, and not able to pass the states back to main window.
Here is the program I wrote:
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
state=[[]]
def popup(x):
def select_clear_states():
global Vars, all_states
states = all_states.get()
if states == 0:
for I in range(len(Vars)):
Vars[I].set(0)
if states == 1:
for I in range(len(Vars)):
Vars[I].set(1)
Vars = []
root = Tkinter.Tk()
all_states = Tkinter.IntVar()
select_all = Tkinter.Checkbutton(root, text = "select/deselect all",variable = all_states, command = select_clear_states)
select_all.grid(row = 0, column = 0, padx = 5, pady = 1)
for n in range(10):
var = Tkinter.IntVar()
Vars.append(var)
checkbox = Tkinter.Checkbutton(root, text = n+1, variable= Vars[n])
checkbox.grid(row = n+1, column = 0, padx = 5, pady = 1)
root.mainloop()
A = Tkinter.Button(top, text ="Hello1",command=lambda: popup(1))
A.pack()
B = Tkinter.Button(top, text ="Hello2",command=lambda: popup(2))
B.pack()
C = Tkinter.Button(top, text ="Hello3",command=lambda: popup(3))
C.pack()
top.mainloop()
am not able to make use of the variables Vars all_state and state[[]], to get he state of the check button.am getting this error
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1536, in __call__
return self.func(*args)
File "C:\Users\Synapse\Documents\Neo\Tutorial\python_tutorial\button.py", line 11, in select_clear_states
states = all_states.get()
NameError: global name 'all_states' is not defined
I should be able to use select/deselectall button and also able to get back all states of each check button to main window.
Example code using class.
It use Toplevel() to create PopUp because Tkinter should have only one Tk() window.
And it use only one mainloop() because more loops make problem with values in variables.
It can created different number of checkboxes.
It needs more work - ie. to return values - but now you can use win.states to get states of all checkboxes (or to set them).
import Tkinter as tk
import tkMessageBox
# --- classes --- (CamelCase names)
class PopUp(tk.Toplevel):
def __init__(self, number=10):
tk.Toplevel.__init__(self)
# - global checkbox to set all "small" checkboxes -
self.global_state = tk.BooleanVar()
cb = tk.Checkbutton(self, text="select/deselect all",
variable=self.global_state,
command=self.select_clear_states)
cb.grid(row=0, column=0, padx=5, pady=1)
# - "small" checkboxes -
self.states = []
for n in range(1, number+1):
var = tk.BooleanVar()
cb = tk.Checkbutton(self, text=str(n), variable=var)
cb.grid(row=n, column=0, padx=5, pady=1)
self.states.append(var)
def select_clear_states(self):
# get global checkbox
state = self.global_state.get()
# set all "small" checkboxes
for x in self.states:
x.set(state)
# --- functions --- (lower_case names)
def popup(num):
win = PopUp(num)
#win.states[1].set(True)
# --- main --- (lower_case names)
root = tk.Tk()
b = tk.Button(root, text="5 checkboxes", command=lambda:popup(5))
b.pack()
b = tk.Button(root, text="10 checkboxes", command=lambda:popup(10))
b.pack()
b = tk.Button(root, text="3 checkboxes", command=lambda:popup(3))
b.pack()
root.mainloop()
I'm making a simple drawing pad program with pygame and I'm making it so you can define your own color. I'm using a tk window to do this but I cant figure out how to get them to work together. Please help, I've been trying to get this to work for hours
Here is my Tk code:
from Tkinter import *
r = 0
g = 0
b = 0
class Custom():
def get_color(self):
self.root = Tk()
self.root.configure(background='black')
self.root.wm_title("Custom")
label1 = Label(self.root, text='Red Value:',bg="black", fg="white")
label1.grid(row=2, column=0,columnspan=2)
self.enter1 = Entry(self.root, bg='white')
self.enter1.grid(row=3, column=0,columnspan=2)
label2 = Label(self.root, text='Green Value:',bg="black", fg="white")
label2.grid(row=4, column=0,columnspan=2)
self.enter2 = Entry(self.root, bg='white')
self.enter2.grid(row=5, column=0, columnspan=2)
label3 = Label(self.root, text='Blue Value:',bg="black", fg="white")
label3.grid(row=6, column=0,columnspan=2)
self.enter3 = Entry(self.root, bg='white')
self.enter3.grid(row=7, column=0, columnspan=2)
btn1 = Button(self.root, text='OK', command=self.close, bg="black",activebackground="green", fg="white")
btn1.grid(row=14, column=0, columnspan=2)
label7 = Label(self.root, bg="black", fg = "white")
label7.grid(row=15, column=0, columnspan=2)
self.enter1.focus()
self.root.mainloop()
def close(self):
self.root.destroy()
def return_color(self):
r = int(self.enter1.get())
g = int(self.enter2.get())
b = int(self.enter3.get())
return (r,g,b)
It works fine, but I can't get it to return the three values to my pygame program.
Here is the pygame snippet:
if key[pygame.K_c]:
import CustomColor
c = CustomColor.Custom()
c.get_color()
self.color = c.return_color()
Current Error:
Traceback (most recent call last):
File "C:/Python27/Drawpad.py", line 75, in <module>
draw.main()
File "C:/Python27/Drawpad.py", line 69, in main
self.update(screen)
File "C:/Python27/Drawpad.py", line 45, in update
self.color = c.return_color()
File "C:/Python27\CustomColor.py", line 41, in return_color
r = int(self.enter1.get())
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2391, in get
return self.tk.call(self._w, 'get')
TclError: invalid command name ".19783112"
I've been tweaking it, but just getting different error messages. If anyone can help, I would appreciate it.
Your immediate problem is that you're trying to access Entry objects after they've been destroyed.
You can fix that very simply:
def close(self):
self.r = int(self.enter1.get())
self.g = int(self.enter2.get())
self.b = int(self.enter3.get())
self.root.destroy()
def return_color(self):
return (self.r,self.g,self.b)
The reason this is happening is that, when you call get_color, that calls self.root.mainloop, which means it can't possibly return until the Tk event loop has exited, which means calling your close method, which means self.root.destroy is guaranteed to have happened before you can call return_color.
Calling a function that blocks on the Tk event loop is going to have other problems as well. Your pygame event loop is stuck waiting for Tk. So, your pygame window can't redraw itself, minimize, or respond to any other events.