When I run this code I get the error message:
File "Start.py", line 22, in <module>
c.lo()
TypeError: lo() takes no arguments (1 given)
I don't know exactly why I am getting this error could someone please explain?
I know it's saying that I put an argument when calling that function but I don't understand why that is?
If someone could shed some light on this issue that would be great.
import subprocess as sp
import Tkinter as Tk
from Tkinter import *
root = Tk()
text = Text(root)
class Console:
def Start():
proc = sp.Popen(["java", "-Xmx1536M", "-Xms1536M", "-jar", ".jar"],stdin=sp.PIPE,stdout=sp.PIPE,)
def lo():
while True:
line = proc.stdout.readline()
text.insert(INSERT,line)
text.pack()
if (line == "Read Time Out"):
proc.stdin.write('stop')
if (line == "Unloading Dimension"):
text.insert(INSERT,"Ready for command")
text.pack()
c = Console()
c.Start()
c.lo()
root.mainloop()
Methods always get the instance as the first argument.
Your method definitions should look like:
def some_method(self):
# do_stuff
In short, that is because lo() is a method of the class Console which is always passed the instance as first argument. So lo() must define a parameter (mostly called self) to hold that argument:
class Console:
def start(self): # functions and methods should have lowercase names
self.proc = sp.Popen(...)
def lo(self):
line = self.proc.stdout.readline()
...
I am surprised that your Start() call worked; it has the same issue.
Related
I've read at least 25 similar questions on this site, and I simply cannot get this working.
As it stands i'm just trying to build a simple chat app with a client and server. The GUI will be running on a separate thread to the logic to ensure things stay fluid and don't lock up. I've trimmed most of the logic out of the code to isolate the problem
import socket, csv, datetime, tkinter as tk, threading
from tkinter import ttk
interface = tk.Tk()
test = tk.StringVar()
test.set("String Var Test")
class serverInterface():
def __init__(self, interface):
global test
self.messageLog = tk.Text(interface, height=10, state="disabled", yscrollcommand="scrollBar.set")
self.scrollBar = ttk.Scrollbar(interface, command=self.messageLog.yview).grid(row=0, column=2, sticky="nsew")
self.messageLog.grid(row=0, column=0, columnspan=2)
test.trace("w", serverInterface.guiUpdate(self))
def guiUpdate(self):
self.messageLog.insert(tk.END, test)
class server():
def __init__(self):
global test
print("Server thread")
while True:
test.set("Updated from server object")
interface.title("Server")
serverInterface = threading.Thread(target=serverInterface(interface)) #Create serverInterface object
server = threading.Thread(target=server, daemon=True) # Create server object
server.start()
interface.mainloop()
This results in the console being spammed with Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__ return self.func(*args) TypeError: 'NoneType' object is not callable
I've also tried to make use of Queue() as I've seen others suggest, but that just results in a different set of errors and I feel using StringVar() is probably the better way of doing this.
I appreciate that there's probably some lines in this code that don't need to be there, they're just leftovers from all the different attempts at bodging it :/
Any solutions would be appreciated.
The error you're asking about is due to this line:
test.trace("w", serverInterface.guiUpdate(self))
That line is functionally identical to this:
result = serverInterface.guiUpdate(self)
test.trace("w", result)
Since guiUpdate(self) returns None, you're asking tkinter to call None. Hence the error TypeError: 'NoneType' object is not callable
The trace method must be given a callable (ie: a reference to a function). In this specific case you need to use self.guiUpdate.
The trace will automatically pass arguments to the function, so you need to properly define the function to accept those arguments. You also have a bug where you're trying to insert an object (test) in the text widget rather than the text contained in the object.
I'm having this problem while trying to multithread with tkinter's mainloop. Everything works if I don't try to multithread, but if I do it gives me an error.
I'm implementing this class to get and set characters coordinates in a certain game and this part works, however the application won't let me quit. I tried setting self.root.protocol's second parameter as self.on_quit() and self.on_quit(self), but it just instantly executes it.
class PositionGUI:
EXIT_FLAG = False
def __init__(self, process: DSProcess):
self.root = Tk()
self.root.protocol("WM_DELETE_WINDOW", self.on_quit)
...
Thread(target=self.update, args=(self, process)).start()
self.root.mainloop()
def update(self, process: DSProcess):
while not self.EXIT_FLAG:
...
def on_quit(self):
self.EXIT_FLAG = True
self.root.destroy()
class DarkShell(DSProcess):
def __init__(self):
super(DarkShell, self).__init__()
...
Thread(target=PositionGUI.__init__, args=(PositionGUI, self)).start()
On-quit method is supposed to set a flag for the update function to finish and close this part of the application, but instead it gives me this error:
"TypeError: on_quit() missing 1 required positional argument: 'self'"
Tkinter needs to be in the main thread if you even really need threading (often you don't there are workarounds for most issue)
Your EXIT_FLAG = Falseis not defined as a class attribute so a call to self.EXIT_FLAG will not work.
Instead of doing from tkinter import * use import tkinter as tk this will prevent any overlapping imports from causing errors.
So without something I can actually test I can only guess at your real problem but take this example and let me know if it helps.
import tkinter as tk
from threading import Thread
class PositionGUI(tk.Tk):
def __init__(self, process: DSProcess):
super().__init__()
self.protocol("WM_DELETE_WINDOW", self.on_quit)
self.EXIT_FLAG = False
...
Thread(target=self.update, args=(self, process)).start()
self.mainloop()
def update(self, process: DSProcess):
while not self.EXIT_FLAG:
pass
def on_quit(self):
self.EXIT_FLAG = True # note that this line does nothing useful
self.root.destroy()
I'm trying to create a simple Gui with tkinter using classes.
But I don't really understand how to make the for-loop work inside the count method, could anyone tell me where should I add the missing argument?
from tkinter import *
import time
class App:
def __init__(self, master):
self.container1 = Frame(master)
self.container1.pack()
self.button1 = Button(self.container1, text="count")
self.button1.bind("<Button-1>", self.count)
self.button1.pack()
def count(self):
for i in range(100):
self.button1["text"] = str(i)
time.sleep(1)
root = Tk()
Myapp = App(root)
root.mainloop()
The error is:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/__init__.py", line 1553, in __call__
return self.func(*args)
TypeError: count() takes 1 positional argument but 2 were given
When you bind an event, a positional argument event is provided to the callback function.
Change your count method to this:
def count(self, event):
You will also need to get rid of time.sleep(1) since .sleep() is a blocking call, which means that it will block the tkinter mainloop which will cause your program to not respond.
This question already has answers here:
Takes exactly 3 arguments (4 given)
(2 answers)
Closed 4 years ago.
I have been trying to find the problem here for hours. From what I can find online people are actually passing more arguments than they think for all the post I can find related to this TypeError. For some reason this problem seams to only happen when I am creating a class that inherits from Toplevel.
Tackback:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\Users\Makin Bacon\workspace\stuff\MINT-master\test3.py", line 12, in fake_error
topErrorWindow(self, message, detail)
File "C:\Users\Makin Bacon\workspace\stuff\MINT-master\test3.py", line 17, in __init__
tk.Toplevel.__init__(self, master, message, detail)
TypeError: __init__() takes from 1 to 3 positional arguments but 4 were given
I even tried to send my arguments to a dummy function that just prints all the arguments and it only printed 3 arguments.
Here is the code I used to test to see what arguments were being passed.
import tkinter as tk
class MintApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
tk.Button(self, text="test error", command=self.fake_error).pack()
def fake_error(self):
message = "test"
detail = "test detail"
topErrorWindow(self, message, detail)
def topErrorWindow(*items):
for item in items:
print("TEST: ", item)
if __name__ == "__main__":
App = MintApp()
App.mainloop()
Here are the results:
TEST: .
TEST: test
TEST: test detail
Now I do not know for sure why I am getting a . for the argument self and I am thinking this might be part of the problem but I cannot find any related issues online.
Here is my code that in my mind should create a top level window with a simple label. Instead I get the trackback error listed above.
import tkinter as tk
class MintApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
tk.Button(self, text="test error", command=self.fake_error).pack()
def fake_error(self):
message = "test"
detail = "test detail"
topErrorWindow(self, message, detail)
class topErrorWindow(tk.Toplevel):
def __init__(self, master, message, detail):
tk.Toplevel.__init__(self, master, message, detail)
tk.Label(self, text = "{}, {}".format(message, detail)).grid(row=0, column=0, sticky="nsew")
if __name__ == "__main__":
App = MintApp()
App.mainloop()
When you do this:
tk.Toplevel.__init__(self, master, message, detail)
You are passing four arguments to __init__: self, master, message, detail. However, as the error clearly states, Toplevel.__init__ takes from one to three arguments.
I don't know what you expect the tkinter Toplevel class to do with message and detail, but they don't map to any of the arguments of a Toplevel.
The solution is to not pass the useless arguments to the superclass constructor since they have meaning to your subclass but not to the superclass:
tk.Toplevel.__init__(self, master)
I am trying to put together a GUI that would read from a continuously updated TXT file and updated every once in a while. So far I succeeded with the first part and I am failing to use 'root.after()' to loop the whole thing but it results in NameError:
import tkinter as tk
root = tk.Tk()
class App:
def __init__(self, root):
frame = tk.Frame(root)
frame.pack()
iAutoInEN = 0
iAvailableEN = 0
self.tkAutoInEN = tk.StringVar()
self.tkAutoInEN.set(iAutoInEN)
self.tbAutoInEN = tk.Label(root, textvariable=self.tkAutoInEN)
self.tbAutoInEN.pack(side=tk.LEFT)
self.button = tk.Button(frame, text="Start", fg="red",
command=self.get_text)
self.button.pack(side=tk.LEFT)
def get_text(self):
fText = open("report.txt") #open a text file in the same folder
sContents = fText.read() #read the contents
fText.close()
# omitted working code that parses the text to lines and lines
# to items and marks them with numbers based on which they are
# allocated to a variable
if iLineCounter == 1 and iItemCounter == 3:
iAutoInEN = int(sItem)
self.tkAutoInEN.set(iAutoInEN)
root.after(1000,root,get_text(self))
app = App(root)
root.mainloop()
try:
root.destroy() # optional; see description below
except:
pass
The first instance runs without any problems and updates the value from 0 to the number in the TXT file but is accompanied with an error
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\...\Python35\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:/.../pythonlab/GUI3.py", line 117, in get_text
self.after(1000,root,get_text())
NameError: name 'get_text' is not defined
EDIT:
When changed to the recommended "self.after(1000,self.get_text)"
class App:
...
def get_text(self):
fText = open("report.txt") #open a text file in the same folder
sContents = fText.read() #read the contents
fText.close()
# omitted code
if iLineCounter == 1 and iItemCounter == 3:
iAutoInEN = int(sItem)
self.tkAutoInEN.set(iAutoInEN)
self.after(1000,self.get_text)
Error changes
Traceback (most recent call last):
File "C:/.../pythonlab/GUI3.py", line 6, in <module>
class App:
File "C:/.../pythonlab/GUI3.py", line 117, in App
self.after(1000, self.get_text)
NameError: name 'self' is not defined
Also please consider this is my very first programme (not only) in Python, so I would appreciate if you are a little bit more explicit with your answers (e.g. when pointing out an indentation error, please refer to an exact line of code).
Because get_text is a method of App class you should call it as self.get_text.
After is a tkinter method. In that case you should call it as root.after. And self refers to the class you are in. So because get_text is a method of current class you should call is with self which is like this in other programming languages like Java.
...
root.after(1000, self.get_text)
...
Firstly, like James commented, you should fix your indentation so that the functions are a part of the class.
Then, change this line
root.after(1000,root,get_text(self))
to this
root.after(1000, self.get_text)
Check out the answer to the following question, which uses the code I just gave you:
Tkinter, executing functions over time