Missing 1 required positional argument: 'x' - python

from tkinter import *
import math
def calculate(x):
while x**2+math.sqrt(x) < 4:
x = x+0.000001
print(x)
gui = Tk()
gui.geometry("300x150")
button = Button(gui, text="Udregn", command=calculate).pack()
gui.mainloop()
I try to use this code and hit the button to make it calculate, however it gives me this error once I press the button instead:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
return self.func(*args)
TypeError: udregn() missing 1 required positional argument: 'x'

Button callbacks are not called with any arguments, which makes sense, because the only information a button provides is that it has been clicked. You'll have to define the function like this:
def calculate():
...
and think about another approach for how to get a value of x for inside the function. Typically, it will come from another GUI component, which you can either access as a global value, or you can have calculate be a bound method of an object that encapsulates x.
class XContainer(object):
def __init__(self, x):
self.x = x
def calculate(self):
while self.x**2+math.sqrt(self.x) < 4:
self.x += 0.000001
print(self.x)
x = XContainer(5)
button = Button(gui, text="Udregn", command=x.calculate)
button.pack()
In this case, some other code will be responsible for creating and possibly modifying x.

Related

How to access to the return value from a function

I'm trying to make an application that can apply sound effects on audio file using PyQt5 module
i developed the module it contain function that apply the effect and return the new value of the signal y
I get stuck on how to get the return value from the module function
effrets.py
for example this function can apply reverberation effects on audio file
def revebration1(y,sr,retard,pert):
T = int(retard*sr)
print(T)
x = np.zeros(len(y)+T)
x[0:len(y)] = y
x[T::] += pert*y
sd.play(x,sr)
return x
app.py
When i click button1 i want to access to access to the value of x returned by revebration1
class AppDemo(QMainWindow):
def __init__(self):
super().__init__()
self.resize(1000,1000)
self.label = QLabel('const', self)
self.layout1=QVBoxLayout()
self.layout2=QVBoxLayout()
#buttons
self.button1 = QPushButton('importer',self)
self.button1.move(300,300)
self.layout1.addWidget(self.button1,1)
#self.button1.clicked.connect(self.lambda)
self.button1.clicked.connect(self.tele)
def tele(self):
# I don't know how to access to the return value of revebration1 function in order to continue building my app
revebrationReturnedValue = revebration1(y,sr,retard,pert)
To access returned value of the function you have to call that function
self.funcResult = revebration1(y,sr,retard,pert) - that's it

What causes an exception in Tkinter callback? [duplicate]

This question already has an answer here:
TypeError: 'NoneType' object is not callable with tkinter
(1 answer)
Closed 1 year ago.
I'm trying to make a program that you can add infinite rooms to, so all of my code is built around using one variable to deduce which room is which. However when I run it, it gives me an error that doesn't directly reference any one line in my code, and since I'm a pretty new programmer, I don't know what it means. Also my code is pretty all over the place and incomplete. Thanks for any help!
The error
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\SCA0023\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
TypeError: 'NoneType' object is not callable
The Code
from tkinter import *
root = Tk()
class Room:
def __init__(self, items):
self.objects = []
self.objects.append(items)
def list(self):
print(self.objects)
def addkitchenmenu(r): #add a new option menu attributed to a new room
globals()[f'kitchenvar_{r}'] = StringVar(root)
globals()[f'kitchenvar_{r}'].set("Add an appliance")
globals()[f'kitchenvar_{r}'].trace('w', applianceadd(r))
kitchenitems = ['Kettle', 'Toaster']
globals()[f'appliancelist_{r}'] = OptionMenu(root, globals()[f'kitchenvar_{r}'], *kitchenitems).pack()
addkitchen(r)
def applianceadd(r): #add a new room
globals()[f'kobjects_{r}'] = []
globals()[f'kobjects_{r}'].append(globals()[f'kitchenvar_{r}'].get())
items = globals()[f'kobjects_{r}']
globals()[f'kroom_{r}'] = Room(items)
globals()[f'kroom_{r}'].list()
def addkitchen(r): #add an appliance
globals()[f'addappliace{r}'] = Button(root, text='add appliance', command=lambda: applianceadd(r))
def newkitchencheck(): #find the next name for a room that isn't taken
varnotfound = True
a = 0
while varnotfound:
if f'kroom{a}' in globals():
a += 1
else:
r = a
varnotfound = False
addkitchenmenu(r)
addroombutton = Button(root, text="add kitchen", command=newkitchencheck)
addroombutton.pack()
root.mainloop()
You are passing result of applianceadd(r) (which is None) to .trace(). Change to .trace("w", lambda *_: applianceaddr(r)).

Timer App Type Error I Can't See

I'm quite new to python I have run into a type error but I personally can't see it. Help will be appreciated. I am using windows 7.
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:\Users\Kids\Desktop\Python Tests\Clock2.py", line 18, in mclock
mlable = Label(mGui, str(z), "minute(s) has past.").pack()
TypeError: __init__() takes from 1 to 3 positional arguments but 4 were given
Code:
import sys
from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
import os
from time import sleep
def mclock():
x = 1
z = 0
while x != -1:
mlable = Label(mGui,text = "str(x) second(s)").pack()
x = x+1
sleep(1)
if x == 60:
x = 1
z = z+1
mlable = Label(mGui, str(z), "minute(s) has past.").pack()
return
mGui = Tk()
mGui.geometry("300x200+100+100")
mGui.title("Jono's Clock")
menubar = Menu(mGui)
filemenu = Menu(menubar, tearoff = 0)
filemenu.add_command(label = "Clock",command = mclock)
menubar.add_cascade(label = "File",menu = filemenu)
mGui.config(menu = menubar)
mGui.mainloop()
Also if any one knows haw to add a clear function to clear the seconds each time it ticks that will be appreciated as well.
The label initializer, like all Python methods, has a self first arguments. It accepts only up to two additional positional arguments (the master and cfg arguments), but you are giving 3:
Label(mGui, str(z), "minute(s) has past.")
You probably wanted to concatenate those two strings; you'll have to pass this in explicitly as the text keyword argument:
Label(mGui, text=str(z) + " minute(s) has past.")

tkinter button press to function call

hey guys first post and what not so hi. anyway trying to make a scientific calculator with tkinter and im not very good with it(and python its my second proper assignment). anyway most of the code will probably be wrong but im just trying to take it one step at a time in particular im concerned about the function add. im calling it via the button however i want to pass the do function a +. this in turn creating an array i can calculate from. it keeps erroring and i dont know how to fix it. its really annoying me now so if someone could help out would be much appreciated
from tkinter import*
from operator import*
class App:
def __init__(self,master):#is the master for the button widgets
frame=Frame(master)
frame.pack()
self.addition = Button(frame, text="+", command=self.add)#when clicked sends a call back for a +
self.addition.pack()
def add(Y):
do("+")
def do(X):#will hopefully colaborate all of the inputs
cont, i = True, 0
store=["+","1","+","2","3","4"]
for i in range(5):
X=store[0+i]
print(store[0+i])
cont = False
if cont == False:
print(eval_binary_expr(*(store[:].split())))
def get_operator_fn(op):#allows the array to be split to find the operators
return {
'+' : add,
'-' : sub,
'*' : mul,
'/' : truediv,
}[op]
def eval_binary_expr(op1, num1, op2, num2):
store[1],store[3] = int(num1), int(num2)
return get_operator_fn(op2)(num1, num2)
root=Tk()
app=App(root)
root.mainloop()#runs programme
Generally speaking, every method in a class should take self as its first argument. The name self is just a convention. It is not a keyword in Python. However, when you call a method such as obj.add(...), the first argument sent to the method is the instance obj. It is a convention to call that instance self in the method definition. So all your methods need to be modified to include self as the first argument:
class App:
def __init__(self, master):#is the master for the button widgets
frame=Frame(master)
frame.pack()
self.addition = Button(frame, text="+", command=self.add)#when clicked sends a call back for a +
self.addition.pack()
def add(self):
self.do("+")
def do(self, X):
...
Note that when you call self.do("+"), inside the method do, X will be bound to "+". Later on in that method I see
X=store[0+i]
which will rebind X to the value store[i]. I don't know what you are trying to do here, but be aware that doing so means you've just lost the "+" value that was just passed in.

Problems with Tkinter Entry and .get()

I'm having problems with my Tkinter Entry widget.
I'm just testing things out and would like to have my callback print out whatever I typed out in Entry self.a. but I'm getting this error.
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in call
return self.func(*args) File "C:/Users/Andy/testimage.py", line 146, in get
print a.get(self) NameError: global name 'a' is not defined
I was wondering if someone can tell me what I'm doing wrong. I linked the callback function correctly because if I make it print "aasdfasd" instead, it will print that when I press the button.
def clicked_wbbalance(self):
self.top = Toplevel()
self.top.title("LASKJDF...")
Label(self.top, text="Enter low level").grid(row=0, column=0,padx=10)
Label(self.top, text="Enter high level").grid(row=1, column=0,padx=10)
Label(self.top, text="Values must be between 0 to 255").grid(row=3, column=0)
Button(self.top, text="Ok", command=self.get).grid(row=3, column = 1)
self.a =Entry(self.top).grid(row=0, column=1,padx=10)
self.b =Entry(self.top).grid(row=1, column=1,padx=10)
def get(self):
print self.a.get(self)
As RocketDonkey pointed out, your traceback does not match the code you posted.
Your code as written will generate a traceback like this:
AttributeError: 'NoneType' object has no attribute 'get'
The root problem is that grid returns None. That means that attributes a and b will be None because they are assigned the result of calls to grid. Fix that by puting object creation and widget placement on different lines:
self.a = Entry(self.top)
self.b = Entry(self.top)
self.a.grid(row=0, column=1,padx=10)
self.b.grid(row=1, column=1,padx=10)
You traceback says print a.get(self) NameError: global name 'a' is not defined, but the code you posted uses the syntax print self.a.get(self) (which would appear to be correct). Therefore if you check on line 146, you aren't prefacing a with self, meaning that instead of referencing the property a of the instance, you are trying to reference a on its own, which is not defined. Try adding self in front of a on line 146 and see if the problem continues.

Categories